rearranging values in an array
I have an array of dictionaries.
Each dictionary have a key "color" and the possible values of color are "red", "green", "blue", "yellow". In the array the dictionaries are added in the order that on fetching the value for key "color" we get "yellow", "green","red" and "blue".
Edit:
I have an array objectsArray of dictionaries.
for(int i=0,i<[objectsArray count];i++)
{
NSDictionary *dict = [objectsArray objectAtIndex:i];
NSLog(@"color: %@\n",[dict valueForKey:@"color"]); //
}
Output:
yellow
green
red
blue
I want output to be
red
green
blue
yellow
How can I do so. Any开发者_如何学C suggestions. Thanx in advance.
'Stole' this from the answer on my own question:
If your array is mutable, you can sort it using the -sortUsing... methods. If not, you can create a new, sorted array using the -sortedArrayUsing... methods. For example, there are -sortUsingComparator: and -sortedArrayUsingComparator: methods which take a comparator block as a parameter. You just need to supply a block that compares two objects using your custom sort order, like this:
[myArray sortUsingComparator:^(id firstObject, id secondObject) {
NSString *firstKey = [firstObject valueForKey:@"color"];
NSString *secondKey = [secondObject valueForKey:@"color"];
if ([firstKey stringEqual:@"red"] || [lastKey stringEqual:@"green"])
return NSOrderedAscending;
else if ([firstKey stringEqual:secondKey])
return NSOrderedSame;
else
return NSOrderedDescending; }];
There's a pretty thorough discussion of sorting arrays, with examples, in the Collections Programming Topics document.
Check out: Obj/C: Sorting an array on a custom order
NSMutableArray *newArray = [objectsArray mutableCopy]
[newArray exchangeObjectAtIndex:3 withObjectAtIndex:4];
[newArray exchangeObjectAtIndex:0 withObjectAtIndex:4];
[objectsArray release];
objectsArray = newArray;
hope this'll help!
You can rearrange objects in an array by various sort methods, check the class reference for details.
Since
精彩评论