-1
我正在嘗試對一系列英雄(對象)進行排序。每個英雄是那種使用多個描述符對對象進行排序
@interface Hero : NSObject <NSCoding>
@property (strong,nonatomic) NSString *name;
@property (strong,nonatomic) NSString *correctAnswers;
@property (strong,nonatomic) NSString *falseAnswers;
@property (strong,nonatomic) NSString *bonus;
@property (strong,nonatomic) NSString *level;
-(NSInteger*) inLevel;
+(Hero*) createHero:(NSString*)name
inLevel:(NSString*)level
withBonus:(NSString*)bonus
correctAnswers:(NSString*)correctAnswers
andFalseOnes:(NSString*)falseAnswers;
- (NSString *)description;
@end
進行梳理這些英雄的數組我寫了一個sortfunction有兩個描述
-(void) sortHeros {
NSSortDescriptor *level = [NSSortDescriptor sortDescriptorWithKey:@"level" ascending:YES comparator:^NSComparisonResult(id a, id b) {
Hero *hero1 = a;
Hero *hero2 = b;
int levelHero1 = [hero1.level intValue];
int levelHero2 = [hero2.level intValue];
if (levelHero1 > levelHero2) {
return (NSComparisonResult)NSOrderedAscending;
} else if (levelHero1 < levelHero2) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSSortDescriptor *bonus = [NSSortDescriptor sortDescriptorWithKey:@"bonus" ascending:YES comparator:^NSComparisonResult(id a, id b) {
Hero *hero1 = a;
Hero *hero2 = b;
int bonusHero1 = [hero1.bonus intValue];
int bonusHero2 = [hero2.bonus intValue];
if (bonusHero1 > bonusHero2) {
return (NSComparisonResult)NSOrderedAscending;
} else if (bonusHero1 < bonusHero2) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedArray;
sortedArray = [self.heros sortedArrayUsingDescriptors:[NSArray arrayWithObjects:level, bonus, nil]];
self.heros = [sortedArray mutableCopy];
}
Unfotunately它同時與
調用sortedArrayUsingDescriptors排序時5個對象的數組崩潰*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bonus]: unrecognized selector sent to instance 0x9674520'
我不知道是怎麼回事。有人可以指出我的錯誤嗎?
-------自我解決----------- 嘿謝謝指出解決方案。這是我的正確的代碼爲其他人有同樣的問題。
@interface Hero ...
-(NSString*) heroBonus;
-(NSString*) heroLevel;
@end
-(void) sortHeros {
NSSortDescriptor *level = [NSSortDescriptor sortDescriptorWithKey:@"heroLevel" ascending:NO comparator:^NSComparisonResult(id a, id b) {
int levelHero1 = [a intValue];
int levelHero2 = [b intValue];
...
}];
NSSortDescriptor *bonus = [NSSortDescriptor sortDescriptorWithKey:@"heroBonus" ascending:NO comparator:^NSComparisonResult(id a, id b) {
int bonusHero1 = [a intValue];
int bonusHero2 = [b intValue];
...
}];
...
}
你有一個NSString *稱爲」獎金「和NSSortDescriptor *稱爲」獎金。「也許只是我,但編譯器也可能會感到困惑 –
顯示你正在收到崩潰的確切線 – Justin
我也會將獎勵排序描述符的名稱改爲sortBonus或者其他東西 – Justin