排序我有下面的類的實例無序數組:與sortedArrayUsingDescriptors和關鍵路徑
@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
,我試圖將其與國家和城市sortedArrayUsingDescriptors排序。 NSSortDescriptor的文檔說,initWithKey的arg是一個關鍵路徑。
但是,如果我嘗試使用NSortDescriptor如:
NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country.city" ascending:YES]autorelease];
我得到一個錯誤:
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.'
我可以用一個關鍵路徑或不是?我究竟做錯了什麼?
請注意'NS(可變)集'不是袋子。如果你想要一個真正的包,也就是說,你可以放置多個物品的集合,使用'NSCountedSet',它總是可變的。 – fzwo 2016-06-21 10:56:23