How to sort an NSMutableArray numerically when it contains objects like follows:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];
The output of the same should be like: P1, P3, P4, P10
How to sort an NSMutableArray numerically when it contains objects like follows:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];
The output of the same should be like: P1, P3, P4, P10
You need to use NSNumericSearch
[array sortUsingComparator:^NSComparisonResult(NSString* _Nonnull str1, NSString* _Nonnull str2) {
return [str1 compare:str2 options:NSNumericSearch];
}];
From the Header Documentation-
NSNumericSearch = 64, /* Added in 10.2; Numbers within strings are compared using numeric value, that is, Foo2.txt < Foo7.txt < Foo25.txt; only applies to compare methods, not find */
Hope this is what you are looking for.
Assuming there is always a character at the start of the strings, then:
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSInteger i1 = [[obj1 substringFromIndex:1] integerValue];
NSInteger i2 = [[obj2 substringFromIndex:1] integerValue];
if (i1 > i2)
return NSOrderedDescending;
else if (i1 < i2)
return NSOrderedAscending;
return NSOrderedSame;
}];
try this code:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"P3",@"P1",@"P4",@"P10", nil];
NSLog(@"Array: %@",array);
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedStandardCompare:)];
NSArray *sorters = [[NSArray alloc] initWithObjects:lastNameDescriptor, nil];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sorters];
NSMutableArray *sortArray = [[NSMutableArray alloc] init];
[sortArray addObjectsFromArray:sortedArray];
NSLog(@"sortArray : %@",sortArray);
Output::
2016-06-15 16:47:47.707 test[5283:150858] Array: (
P3,
P1,
P4,
P10
)
2016-06-15 16:47:47.708 test[5283:150858] sortArray : (
P1,
P3,
P4,
P10
)
You can also sort NSArray
or NSMutableArray
using NSSortDescriptor
.
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSArray *sortedArray = [<arrayToBeSorted> sortedArrayUsingDescriptors:@[sd]];
NSLog(@"Result = %@", sortedArray);