sorting - Sort two-dimensional NSMutableArray using the last element the inner arrays -
i have following nsmutablearray:
(a|b|c|d|e|255, f|g|h|i|j|122, k|l|m|n|o|555)
i trying sort objects in array using last component (255, 122, 555). right have following code:
[myarray sortusingselector:@selector(localizedcaseinsensitivecompare:)];
as expected, method sorts array first element (a, f, k).
i read nssortdescriptor, example:
nssortdescriptor *sort = [[[nssortdescriptor alloc] initwithkey:@"datemodified" ascending:yes] autorelease];
if use it, not clear put parameter in initwithkey
.
you can use sort descriptor, takes last object of "inner" arrays , sort that.
since sort descriptors use key-value coding (kvc), need aware arrays respond valueforkey:
in special way - pass normal key on each of objects contain.
you need know methods not take parameter and return value can accessed through kvc if normal properties.
all adds following:
- each of objects contained in array (i.e., inner arrays) have key want sort by:
lastobject
- but since objects instances of
nsarray
pass key on objects they contain - not want. - you therefore need use special escape in key name situation,
@
, making actual key use@lastobject
so make long story short, can want in way:
nsmutablearray *array = ... // array nssortdescriptor *sd = [nssortdescriptor sortdescriptorwithkey: @"@lastobject" ascending: yes selector: @selector(localizedcaseinsensitivecompare:)]; [array sortusingdescriptors: @[sd]];
you'll notice "@" in key name, within string.
this escape character works other collection classes, instance if want access allkeys
dictionary through kvc, key should use @allkeys
.
Comments
Post a Comment