Sort a NSMutableArray in objective-c? - xcode

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

Related

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:

how to sort NSMangedObjects by its NSDate attributes

Question is short:
I have an array of some NSManagedObjects,
all of them have an NSDate attribute
Now I want to sort this arry by their date, the latest the first,
how could implement this?
You want to use NSArray's sortedArrayUsingDescriptors: method with an NSSortDescriptor. If your array is called array and the NSDate attribute is called date, then this would work:
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"date" ascending:NO]];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
Also, note that when you're getting these NSManagedObjects using an NSFetchRequest, you can give the request sortDescriptors so that they're already sorted. Using the same sortDescriptors from above, just do the following before executing the request:
request.sortDescriptors = sortDescriptors;

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.

How to sort NSMutableArray of NSMutableDictionary?

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.

Resources