I have an unordered array with instances of the following class:
@interface Place : NSObject {
}
@property (nonatomic, copy) NSString *country;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, retain) NSURL *imageURL;
-(id) initWithCountry: (NSString *) aCountry city: (NSString *) aCity imageUrl: (NSURL *) aUrl;
@end
and I'm trying to sort it with sortedArrayUsingDescriptors by country and city. The docs for NSSortDescriptor say that the arg of initWithKey: is a Key Path.
However, If I try to use a NSortDescriptor such as:
NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];
I get an error:
NSMutableSet *bag = [[[NSMutableSet alloc] init] autorelease];
[bag addObject:[[Place alloc] initWithCountry:@"USA"
city:@"Springfield"
imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];
[bag addObject:[[Place alloc] initWithCountry:@"Afghanistan"
city:@"Tora Bora"
imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];
[bag addObject:[[Place alloc] initWithCountry:@"USA"
city:@"Chicago"
imageUrl:[NSURL URLWithString:@"http://www.agbo.biz"]]];
[bag addObject:[[Place alloc] initWithCountry:@"USA"
city:@"Chicago"
imageUrl:[NSURL URLWithString:@"http://www.google.com"]]];
NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];
NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: sort, nil]];
* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSCFString 0x6ae8> valueForUndefinedKey:]: this class is not key value coding-compliant for the key city.'
Can I use a key path or not? What am I doing wrong?
NS(Mutable)Set
is not a bag. If you want a real bag, that is, a collection where you can put more than one of each item, useNSCountedSet
, which is always mutable. – fzwo