我不明白如何使用谓词,我有一个很长的代码来按属性“类型”从数组中过滤对象,突然我看到了方法“filteredArrayUsingPredicate”,它可以让我的生活变得更好。我尝试编写谓词,但总是出错;有人可以告诉我如何正确写吗?
我有方法- (void) filterData: (NSString *)filteredWord
:
我还有带有对象(事件)的数组:NSArray *eventsArray。 我想使用filteredArrayUsingPredicate来获取带有对象(事件)的新数组,其中它们的属性(类型)等于filterWord。请注意,Event 是 Core Data Managed 子类。
是否可以使用谓词来做到这一点?
我的尝试之一:
NSString *propertyName = @"type";
NSArray *eventsArray = [[[[self currentPerson] events] objectEnumerator]allObjects];
NSPredicate *predicte = [NSPredicate predicateWithFormat:@"%k like '%@'",propertyName,filteredWord];
[eventsArray filteredArrayUsingPredicate:predicte];
最佳答案
试试这个:
NSString *propertyName = @"type";
NSArray *eventsArray = [[[self currentPerson] events] allObjects];
NSPredicate *predicte = [NSPredicate predicateWithFormat:
@"%k like %@",propertyName, filteredWord];
NSArray *filteredArray = [eventsArray filteredArrayUsingPredicate:predicte];
您忽略过滤结果。 filteredArrayUsingPredicate:
返回 NSArray 的新实例。它不会过滤原始内容
数组就位,因为 NSArray
对象是不可变的。你要么
必须做一个
NSMutableArray
然后使用 filterUsingPredicate:
就地过滤数组,或者
你必须对返回的数组做一些事情
filteredArrayUsingPredicate:
(记录、保存等...)
不要在属性周围使用单引号。 (感谢@MartinR 的线索)
关于objective-c - 使用filteredArrayUsingPredicate方法通过属性从数组中过滤对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13901646/