How to sort NSMutableArray of NSMutableDictionary? - cocoa

I have NSMutableArray of NSMutableDictionary(NSString objects). One of NSString object is actually a date, and i need to sort NSMutableArray based on that date and I don't want it to sort dates as strings. How can i make it?

If I understand correctly, your array contains dictionaries that contain strings and you want to sort on those strings... as dates. Something like this perhaps:
[someArray sortWithOptions: 0 usingComparator: ^(id inObj1, id inObj2) {
NSDate *date1 = [NSDate dateWithString: [inObj1 objectForKey: #"dateString"]];
NSDate *date2 = [NSDate dateWithString: [inObj2 objectForKey: #"dateString"]];
return [date1 compare: date2];
}];

You will need to use the sortedArrayUsingFunction:context: method. For example:
NSInteger comparator( NSDictionary *d1, NSDictionary *d2, void *context )
{
return [[d1 objectForKey:#"date"] compare:[d2 objectForKey:#"date"]];
}
// In some method:
NSArray *sortedArray = [array sortedArrayUsingFunction:comparator context:nil];
Note: This is not tested.

Related

NSString to NSArray and iterate

I have a code that creates an NSString and separates value with a comma. What I need to do is take that string, convert it to a NSArray and separate each value from the NSString between the commas, then iterate through each one. The code below returns the array as a single string
NSString *emails = #"testemail#gmail.com, testemail2#gmail.com";
NSArray *listItems = [emails componentsSeparatedByString:#", "];
for (int i = 0; i < [listItems count]; i++) {
NSString *address = (NSString*) [listItems objectAtIndex:i];
NSLog (#"ADDRESS: %#", address);
The Log shows the response testemail#gmail.com, testemail2#gmail.com when I want it to separate each one individually. Should this be an NSMutableArray instead?
The code is correct. You'll get two (separate) lines starting with ADDRESS:
But nowadays (actually since 2009!) it's highly recommended to use Fast Enumeration if the loop index is not needed
NSString *emails = #"testemail#gmail.com, testemail2#gmail.com";
NSArray *listItems = [emails componentsSeparatedByString:#", "];
for (NSString *email in listItems) {
NSLog(#"ADDRESS: %#", email);
}

Building up an array an element at a time

Currently I'm populating an array in one line, e.g.
self.monthMonths = [[NSArray alloc] initWithObjects:#"January", #"February", #"March", #"April", #"May", #"June",#"July",#"August",#"September",#"October",#"November",#"December", nil];
What is the syntax to add these elements one at a time as I want to pull the data from a database. I'm using the months of the year as an example.
while([results next]) {
NSString *months = [results stringForColumn:#"month"];
self.month = [[NSArray alloc] initWithObjects:#"month",nil];
//[NSArray
NSLog(#"Month: %#",month);
}
Create an NSMutableArray and add the objects to it one by one with addObject
You need to use NSMutableArray instead, and call -addObject:

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

How to sort a mutablensarray?

I made this code to sort an nsmutablearray but how to send back an NSMutablearray ? i need this because a add information later in my mutablearray.
-(NSArray*)trierTableau:(NSMutableArray*)ptableau champsFiltre:(NSString*) champs{
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:champs
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors = [NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray = [ptableau sortedArrayUsingDescriptors:descriptors];
return sortedArray;
}
If you want to sort your NSMutableArray in-place, then you could call sortUsingDescriptors: instead of sortedArrayUsingDescriptors:, which returns a sorted copy of your array. sortUsingDescriptors: will sort the existing NSMutableArray.
e.g.
-(void)trierTableau:(NSMutableArray*)ptableau champsFiltre:(NSString*) champs {
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:champs
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors = [NSArray arrayWithObjects:lastDescriptor, nil];
[ptableau sortUsingDescriptors:descriptors];
}
This way you don't have to return the NSMutableArray either.
If you actually want a sorted copy of the array, then you'll need to create a new NSMutableArray, use addObjectsFromArray: to copy the elements over, and then use sortUsingDescriptors: on the new array. But I think that sorting the existing NSMutableArray is probably what you'll want.

Sort a NSMutuableArray

I have a NSMutableArray that is loaded with a inforamtion from a dictionary...
[self.data removeAllObjects];
NSMutableDictionary *rows = [[NSMutableDictionary alloc] initWithDictionary:[acacheDB.myDataset getRowsForTable:#"sites"]];
self.data = [[NSMutableArray alloc] initWithArray:[rows allValues]];
There are two key value pairs in the rows dictionary.
I need to sort the self.data NSMutableArray in alphabetical order.
How is this accomplished??
thanks
tony
If the values are plain strings you can use the following to create a sorted array:
NSArray *sorted = [values sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
This should do:
[self.data removeAllObjects];
NSArray *values = [[acacheDB.myDataset getRowsForTable:#"sites"] allValues];
NSSortDescriptor *alphaDescriptor = [[NSSortDescriptor alloc] initWithKey:#"DCFProgramName" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedValues = [values sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDescriptor, nil]];
[alphaDesc release];
[self.data addObjectsFromArray:sortedValues];
There's no need to clear an NSMutableArray if you're replacing it shortly afterwards.
There's no need to create an additional NSMutableDictionary, if you're not modifying anything in it.
There's no need to create an additional NSMutableArray, if you could just as well just add the values to the existing one.
Also: There are some serious memory leaks in your code. (2x alloc + 0x release = 2x leak)
Edit: updated code snippet to reflect OP's update on data structure.

Resources