[英]Can't make NSPredicate work on custom NSObject
我有一個名為SCPFLocation
的自定義對象的NSSet
,我想用每個位置的人類可讀格式(一個稱為interpretedForm
的屬性)對其進行過濾。 這是我的做法:
NSMutableSet *set = [[SCPFLocation allLocations] mutableCopy];
[set filterUsingPredicate:[NSPredicate predicateWithFormat:@"interpretedForm contains[c] '%@'", searchString]];
self.matches = [set.allObjects sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [((SCPFLocation *)obj1).interpretedForm compare:((SCPFLocation *)obj2).interpretedForm];
}];
但我不知道為什么這不起作用。 在應用謂詞過濾器時, set
包含零個對象。 我可能做錯了什么?
SCPFLocation
是SCPFLocation
的子類, SCPFValue
從SCPFLocation
繼承並覆蓋interpretedForm
屬性。 以下是@implementation
的@interface
和SCPFLocation
。
@interface SCPFLocation : SCPFValue
@property (strong, nonatomic) NSString *province;
@property (strong, nonatomic) NSString *city;
@end
@implementation SCPFLocation
- (NSString *)interpretedForm
{
if (self.city) {
return [NSString stringWithFormat:@"%@, %@", self.city, self.province];
} else {
return self.province;
}
}
@end
和SCPFValue.h
:
@interface SCPFValue : NSObject
/*! The human-readable representation of this @c SCPFValue.
*/
@property (strong, nonatomic) NSString *interpretedForm;
/*! A representation of this @c SCPFValue when it is being passed from and to the API.
*/
@property (strong, nonatomic) NSString *originalForm;
- (id)initWithInterpretedForm:(NSString *)interpretedForm originalForm:(NSString *)originalForm;
@end
您不必像這樣在塊內強制轉換對象。 我發現此表格更易於閱讀。
NSMutableSet *set = [[SCPFLocation allLocations] mutableCopy];
[set filterUsingPredicate:[NSPredicate predicateWithFormat:@"interpretedForm contains[c] '%@'", searchString]];
self.matches = [set.allObjects sortedArrayUsingComparator:^NSComparisonResult(SCPFLocation *obj1, SCPFLocation *obj2) {
return [obj1.interpretedForm compare:obj2.interpretedForm];
}];
話說回來。 那里什么都行不通。 它怎么不起作用?
您能顯示一個不起作用的對象和搜索字符串的示例嗎?
我自己弄清楚了,答案很令人沮喪。 不用這樣定義謂詞:
[NSPredicate predicateWithFormat:@"interpretedForm contains[c] '%@'", searchString]
我這樣做是這樣的:
[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"interpretedForm contains[c] '%@'", searchString]]
和它的工作。 我不知道為什么第一種形式非常遵循Apple的Predicate Format String Syntax時為什么會有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.