cocoa - 使用 nspredicate 使用字典过滤数组失败

标签 cocoa nsarray nsdictionary nspredicate

我正在尝试使用谓词从 NSMutableArray 中获取 NSDictionary:

NSMutableArray *arr = [NSMutableArray arrayWithArray:[self createArrayFromCSV:savedCSV withDelimiter:delim firstLineContainsKeys:YES]];

// The method «createArrayFromCSV returns an array of dictionaries

NSLog(@"Array %@", [arr objectAtIndex:0]);  // works fine

// spits out: 

// Array {
//     product = "MyProduct";
//     "id_product" = 29;
// }

// idField and idVal are passed to the method

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ == %@)", idField, idVal];

NSLog(@"predicate %@", predicate);

// spits out predicate "id_product" == "29"

NSArray *filtered = [arr filteredArrayUsingPredicate:predicate];

NSLog(@"Filtered %@", filtered);

// Filtered is always empty

有什么想法我做错了吗???

[已解决] 显然,我弄错了格式字符串。这有效:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", idField, idVal];

根据这篇文章NSPredicate predicateWithFormat passing in name of attribute

对于键或键路径,必须使用@K

最佳答案

显然,我把格式字符串弄错了。这有效:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", idField, idVal];

根据这篇文章NSPredicate predicateWithFormat传入属性名称

对于键或键路径,必须使用@K

关于cocoa - 使用 nspredicate 使用字典过滤数组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751227/

相关文章:

cocoa - NSOutlineView 和 NSTreeController 可以处理数千个对象吗?

swift - 存储工作 TableView Controller 的窗口大小

cocoa - 如何调用NSCell的fieldEditorForView : to assign custom field editor

iphone - NSMutableDictionary 没有正确初始化

iphone - 无法设置对象:forKey: in NSMutableDictionary

ios - 如何从 NSDictionary 获取键/值对?

cocoa - NSTabView 中非事件选项卡的窗口大小调整和 View 更新

ios - 如何按给定大小的 block 从字符串拆分为数组

nsarray - 在UIPasteboard中存储NSArray

ios - Swift Plist 读取和初始化数组作为键的对象