Sorting Array of Custom Class Objects - iphone

I am facing problem that is of sorting. The scenario is explained as: i have a class (Suppose of person) and it has suppose 4 attributes (firstName, lastName, Address, salary) i am creating its object and making a collection of all attributes and putting this object in a NSMutableArray and so on. So at every index of array i have one object (i.e collection of 4 attributes). Now i want to sort that array on the basis of salary can anyone help me out regarding this problem, will be thankful.,

See the documentation for NSArray. It has several sorting methods. Search for the word "sort" and you'll find 'em. (You'll want either the block based or function based API).

use this
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:#"salary" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[yorArrary sortUsingDescriptors:sortDescriptors];

Either you implement a compare-method for your object:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:#selector(compare:)];
or usually even better: (The default sorting selector of NSSortDescriptor is compare:)
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

Related

Objective-c: how to sort a NSMutableArray of UIButtons using their tags

I have a NSMutableArray containing UIButtons. I have given each of the buttons a unique
tag. The buttons will be added to the array in random order, but i want to later sort it so that the buttons are in ascending order with respect to their tags.
Thanks for the help!
Yeap.
Try this:
NSSortDescriptor *ascendingSort = [[NSSortDescriptor alloc] initWithKey:#"tag" ascending:YES];
NSSortDescriptor *descendingSort = [[NSSortDescriptor alloc] initWithKey:#"tag" ascending:NO];
NSArray *sortedArray = [someArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:ascendingSort]];
You can use the NSSortDescriptor to sort a NSArray.
NSArray *unsortedArray = ...
NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"tag" ascending:YES]]];
There are multiple "sortedArrayUsing..." functions. Use the one that seems to fit your needs the best.
(BTW, remember that, since NSMutableArray is a subclass of NSArray, all of the methods of NSArray apply to NSMutableArray as well.)

How can I sort an NSMutableArray alphabetically?

I want to sort an NSMutableArray alphabetically.
You can do this to sort NSMutableArray:
[yourArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
The other answers provided here mention using #selector(localizedCaseInsensitiveCompare:)
This works great for an array of NSString, however the OP commented that the array contains objects and that sorting should be done according to object.name property.
In this case you should do this:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
Your objects will be sorted according to the name property of those objects.
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES]; // Describe the Key value using which you want to sort.
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; // Add the value of the descriptor to array.
sortedArrayWithName = [yourDataArray sortedArrayUsingDescriptors:descriptors]; // Now Sort the Array using descriptor.
Here you will get the sorted array list.
In the simplest scenarios, if you had an array of strings:
NSArray* data = #[#"Grapes", #"Apples", #"Oranges"];
And you wanted to sort it, you'd simply pass in nil for the key of the descriptor, and call the method i mentioned above:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:#[descriptor]];
The output would look like this:
Apples, Grapes, Oranges
For more details check this
Use the NSSortDescriptor class and rest you will get every thing here
NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Name_your_key_value" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray;
sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];
Maybe this can help you:
[myNSMutableArray sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:#"lastName" ascending:YES]]];
All is acording to NSSortDescriptor...

display data in alphabetical order iphone

How to display xml parsed Data in UITableView In alphabetical order.?
In order to display/arrange your data in alphabetical which in a array you have to use NSSortDescriptor
you have to make the object of this NSSortDescriptor class and give data here which you are fetching from XML
NSSortDescriptor *itemXml = [[NSSortDescriptor alloc] initWithKey:#"itemName" ascending:YES];
Now suppose you have an array sortDescriptors
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:itemXml,nil];
[yourArray sortUsingDescriptors:sortDescriptors];
Now give the yourArray to your UITableView delegate methods...... you will get the sorted data on table
NSSortDescriptor *sorter;
sorter = [[NSSortDescriptor alloc]initWithKey:#"Category" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sorter];
[categoryListArray sortUsingDescriptors:sortDescriptors];
[sorter release];
Try This
Actually there are lots of different ways to sort arrays.
Sort descriptors are only one example.
Others are sortedArrayUsingComparator, sortedArrayUsingFunction:context, sortedArrayUsingSelector, and new to Mac OS 10.6 and iOS 4.0, sortedArrayWithOptions:usingComparator.
Those are NSArray methods that return a sorted array.
NSMutableArray also has variations on those methods that sort the mutable array "in place".

Sorting an NSArray of NSDictionary

I have to sort an array of dictionaries but I have to order by an object in the dictionaries.
Use NSSortDescriptors with -sortedArrayUsingDescriptors:. For the key path, pass in the dictionary key, followed by the object's key(s) by which you want to sort. In the following example, you have an array of dictionaries and those dictionaries have a person under "personDictionaryKey", and the "person" has a "lastName" key.
NSSortDescriptor * descriptor = [[[NSSortDescriptor alloc] initWithKey:#"personInDictionary.lastName"
ascending:YES] autorelease]; // 1
NSArray * sortedArray = [unsortedArray sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptor]];
1 - In 10.6 there are class convenience methods for creating sort descriptors but as bbum's answer says, there are now blocks-enabled sorting methods and I'm betting they're a lot faster. Also, I noticed your question is for iOS, so that's probably irrelevant. :-)
To rephrase; you want to sort the array by comparing dictionary contents? (I.e. you know you can't sort a dictionary's contents, right?)
As Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:. This is quite likely the best solution; at least the most straightforward.
There are other ways, too.
Assuming you are targeting iOS 4.0, then you can use sortedArrayUsingComparator: and pass a block that'll do the comparison of the two dictionary's contents.
If you are targeting iOS 3.x (including the iPad), then you would use sortedArrayUsingFunction:context:.
Or, as Joshua suggested, use NSSortDescriptor and sortedArrayUsingDescriptors:
All are quite well documented, with examples.
here is an implementation with custom objects instead of dictionaries:
ArtistVO *artist1 = [ArtistVO alloc];
artist1.name = #"Trentemoeller";
artist1.imgPath = #"imgPath";
ArtistVO *artist2 = [ArtistVO alloc];
artist2.name = #"ATrentemoeller";
artist2.imgPath = #"imgPath2";
ArtistVO *artist3 = [ArtistVO alloc];
artist3.name = #"APhextwin";
artist3.imgPath = #"imgPath2";
//NSLog(#"%#", artist1.name);
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:artist1];
[arr addObject:artist2];
[arr addObject:artist3];
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"name"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray =
[arr sortedArrayUsingDescriptors:descriptors];
NSLog(#"\nSorted ...");
NSEnumerator *enumerator;
enumerator = [sortedArray objectEnumerator];
ArtistVO *tmpARt;
while ((tmpARt = [enumerator nextObject])) NSLog(#"%#", tmpARt.name);

Sorting an Array of custom objects by a dictionary included in the custom object: How?

I have an array of custom objects. The objects includes a dictionary.
Something like this:
CustomDataModel *dataModel;
dataModel.NSString
dataModel.NSDictionary
dataModel.image
I'd like to sort by one of the objects in the dictionary:
dataModel.NSDictionary ObjectWithkey=#"Name"
The dataModel gets loaded into an NSArray. I now want to sort the by the #"Name" key in the dictionary. Is this something NSSortDescriptor can handle? Basic sort works fine, just haven't figured this one out yet...
Your question isn't completely clear to me, but you can try something like this on your NSArray:
- (NSArray *)sortedItems:(NSArray*)items;
{
NSSortDescriptor *sortNameDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"Name" ascending:NO]
autorelease];
NSArray *sortDescriptors =
[[[NSArray alloc]
initWithObjects:sortNameDescriptor, nil]
autorelease];
return [items sortedArrayUsingDescriptors:sortDescriptors];
}
//Sort an array which holds different dictionries - STRING BASED - Declare it in the .h
- (NSArray *)sortStringsBasedOnTheGivenField:(id)dictionaryKey arrayToSort:(NSMutableArray *)arrayToHoldTemp ascending:(BOOL)ascending {
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:dictionaryKey ascending:ascending selector:#selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor];
[arrayToHoldTemp sortUsingDescriptors:descriptors];
[nameDescriptor release];
return arrayToHoldTemp;
}
Usage:
self.mainArrayForData = [NSArray arrayWithArray:[self sortNumbersBasedOnTheGivenField:#"Name" arrayToSort:arrayWhichContainsYourDictionries ascending:YES]];
the above method is good for an array that holds dictionaries