Sorting NSMutableArray with NSStrings in alphabetical order - sorting

I have a NSMutableArray with NSStrings and I want to sort them in alphabetical order, seems it's no hard, but I didn't find nice solution. Help me please.

Using sortUsingSelector: method with compare: as comparing selector:
NSMutableArray* strings = [NSMutableArray arrayWithObjects:#"dog", #"ant", #"cat",nil];
[strings sortUsingSelector:#selector(compare:)];
NSLog(#"%#", strings);

Related

filtering objects from nsmutablearray with a nsarray of string values

I have a NSMutableArray called "scoreBoard" which has hundreds of objects with properties name,score,id
I also have a NSArray called "friends" with a list of strings
I want to scan all objects "id" from "scoreBoard" with NSArray "friends" and keep only the objects which property value id matches the list of "friends"
can anyone give me some directions?
Something like this:
NSIndexSet *toRemove = [scoreBoard indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [friends containsObject:obj.name];
}];
[scoreBoard removeObjectsAtIndexdes:toRemove];
Note this isn't optimally fast. You might also want to look at [NSMutableArray filterUsingPredicate:] although NSPredicate isn't my preference.

Sort NSMutableArray for a key with float datatype

I have a NSMutableArray with data:
Name ... Male ... Age ... Point
("David"..."Male"...18...7.25)
("Mary"..."Female"...16...20.50)
("Kend"..."Male"...17...4.50)
("Frank"..."Male"...25...27.50)
("Cain"..."Female"...28...2.25)
("Sims"..."Female"...17...10.50)
...
I want to sort this NSMutableArray by key Point. I tried:
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Point" ascending:NO];
[self.arrayPupils sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
and output:
David/Male/18/7.25
Kend/Male/17/4.50
Frank/Male/25/27.50
Mary/Female/16/20.50
Cain/Female/28/2.25
Sims/Female/17/10.50
But expected result are:
Frank/Male/25/27.50
Mary/Female/16/20.50
Sims/Female/17/10.50
David/Male/18/7.25
Kend/Male/17/4.50
Cain/Female/28/2.25
Help me pls... Many thanks.
Your sort is sorting by Age. You need to instead sort by "Point" to get that output.

NSArray Sorting

I have an NSArray with values that I am pulling from an NSDictionary using a selector to sort with which has the following values:
John
Brian
Alex
....
Dave
When I use the code below, since they are being compared as strings, the list comes back with:
NSArray *array = [[[self myDictionary] allValues] sortedArrayUsingSelector:#selector(compare:)];
John
Dave
Brian
...
How can I get these values to sort correctly where they are in order 1, 2, 3, etc.? I've looked at several different examples for sorting, but have not been able to find an example like mine. I must also mention that I'm new to objective-c and iOS. Any help would be greatly appreciated.
Thanks!
I was actually able to figure out the solution. I created an NSComparisonResult block using custom logic to read the number portion off of the front of each string and then comparing them numerically:
NSComparisonResult (^sortByNumber)(id, id) = ^(id obj1, id obj2)
{
//Convert items to strings
NSString *s1 = (NSString *)obj1;
NSString *s2 = (NSString *)obj2;
//Find the period and grab the number
NSUInteger periodLoc1 = [s1 rangeOfString:#"."].location;
NSString *number1 = [s1 substringWithRange:NSMakeRange(0, periodLoc1)];
NSUInteger periodLoc2 = [s2 rangeOfString:#"."].location;
NSString *number2 = [s2 substringWithRange:NSMakeRange(0, periodLoc2)];
//Compare the numeric values of the numbers
return [number1 compare:number2 options:NSNumericSearch];
};
Then I sort my array by calling:
NSArray *array = [[[self myDictionary] allValues] sortedArrayUsingComparator:sortByNumber];

Sort a NSMutableArray in objective-c?

I am working on NSMutable Array containing list of "First Name" in it.I want to sort it alphabatically.
I tried this code
NSSortDescriptor * sortFriend = [[[NSSortDescriptor alloc] initWithKey:kfirstName ascending:YES] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortFriend];
NSArray * sorted = [Friendsarr sortedArrayUsingDescriptors:descriptors];
correct me if i am wrong.I do have an array of names also if that could be used.
Thanks
I tried the code
NSSortDescriptor * sortFriend = [[[NSSortDescriptor alloc] initWithKey:kfirstName ascending:YES selector: #selector(caseInsensitiveCompare:)] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortFriend];
NSArray * arrmp = [temparray sortedArrayUsingDescriptors:descriptors];
But still my result contain 2 'k' chars. one 'k' and 'K'.I want to have case insensitive result
If your NSMutableArray only contains objects of type NSString, simply do:
[myMutableArray sortUsingSelector:#selector(compare:)];
You can sort NSMutable array case insensitively by this code
NSSortDescriptor *sorter=[[[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:#selector(caseInsensitiveCompare:)]autorelease];
NSArray *sortdescriptor=[NSArray arrayWithObject:sorter];
[cpy_arr_Service_Name sortUsingDescriptors:sortdescriptor];
I found the solution of sorting NSMutableArrays with sample code which can be found on the site below.
http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/
I hope it help others to as it provides indexed sorting of a grouped table view using an array as the datasource

sorting an NSArray of NSDates

I have an NSArray of NSDate objects and I want to sort them so that today is at 0, yesterday at 1 etc.
Is it ascending or descending, and do i use a function, selector or what?
There are different sort methods for NSArray because there may be different ways you want to sort things. NSSortDescriptors are a general way that give you a lot of options as far as what keys to use in sorting, what selectors you want to use on those keys, and overall order to use, etc. Or you can use functions or comparator blocks instead if your case requires that or if that's more convenient for your particular case.
To answer your first question, if you want today to be first, followed by yesterday then, yes, that is of course descending order.
To sort some dates in descending order you can just do this: (assuming an NSArray full of NSDates called 'dateArray'):
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
[descriptor release];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
Or, if you are building for iOS 4+ or Snow Leopard+ you can do this:
NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator:
^(id obj1, id obj2) {
return [obj2 compare:obj1]; // note reversed comparison here
}];
Try this magic:
Sort array of dates in ascending order.
i.e. dates getting later and later, or to put it another way, dates going into the future.
NSArray ascendingDates = [dates sortedArrayUsingSelector:#selector(compare:)];
Sort array of dates in descending order. (what the question asked)
i.e. dates getting earlier and earlier, dates going into the past or to put it another way: today is at index 0, yesterday at index 1.
NSArray* descendingDates = [[[dates sortedArrayUsingSelector:#selector(compare:)] reverseObjectEnumerator] allObjects];

Resources