I have an array which contains 2 objects. Each object has a “type” key. One of the values for that key is “resource” and the other is “crop”.
I want to sort through that array and create a new array which only contains the objects of the type I need. I thought this code did that…
-(NSArray*)getItemsOfType:(NSString *) type
{
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:type
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [templateObjects sortedArrayUsingDescriptors:sortDescriptors];
return sortedArray;
}
But all it seems to do is just sort the current array into some kind of order. How can I change that function to do what I need? so I need to use “initWithKey:ascending:selector:” ?
UPDATE
I just tried this code above the code above…
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"templateObjects.type like %@", type];
NSArray *newArray = [templateObjects filteredArrayUsingPredicate:predicate];
But newArray just appears to be empty? I have a feeling the @”templateObjects.type” part is wrong?
Update 2
ok this code does what I need it to..
-(NSArray*)getItemsOfType:(NSString *) type
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type CONTAINS[cd] %@", type];
NSArray *newArray = [templateObjects filteredArrayUsingPredicate:predicate];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:type
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [newArray sortedArrayUsingDescriptors:sortDescriptors];
return sortedArray;
}
use
instead of
so
or
This will work as you said both objects have the type key.