objective-c - 使用filteredArrayUsingPredicate方法通过属性从数组中过滤对象

标签 objective-c ios nsarray nspredicate predicatewithformat

我不明白如何使用谓词,我有一个很长的代码来按属性“类型”从数组中过滤对象,突然我看到了方法“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/

相关文章:

ios - 将复选框列表添加到 UIAlertController

ios - 如何整合照片库

ios - 显示网络图像是使用 NSAllowsArbitraryLoads 的正当借口?

objective-c - NSMutableArray 不使用 addObjectsFromArray 添加任何内容

ios - View 和标签栏之间的 UITabBar 线

ios - 如何将 Get 请求 AFNetworking 中的 responseObject 保存到 nsarray?

iphone - uitableview 单元格中的自定义复选框出现错误

iOS 13.1 PDFKit PDFView.go(到页面 :) isn't working

objective-c - MKMapView:显示或隐藏注释数组而不循环

ios - 将 NSArray 写入计算机上的文件一次