【发布时间】:2013-08-30 22:08:02
【问题描述】:
首先:对不起,如果标题不是很清楚,我无法将我的问题用简短的语言表达出来!
请考虑以下情况:
- 您正在使用 Core Data 来存储对象
- 你想从你的上下文中获取对象
- 您想包含一个谓词以仅获取具有某些属性的对象
- 您有一个包含键值对的 NSDictionary,其中键代表属性名称,值代表要匹配的所需值
如何最好地实现这一目标?
我目前有以下方法,这是实现此目的的一种快速且可能效率低下的方法:
NSDictionary *attributes = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:@"value1", @"value2", nil] forKeys: [NSArray arrayWithObjects:@"attr1", @"attr2", nil] ];
// Build predicate format
NSString *predicate = @"";
NSMutableArray *predicateArguments = [[NSMutableArray alloc] init];
int index = 0;
for (NSString *key in attributes) {
NSString *value = [attributes objectForKey: key];
predicate = [predicate stringByAppendingFormat: @"(%@ = %@) %@", key, @"%@", index == [attributes count]-1 ? @"" : @"AND "];
[predicateArguments addObject: value];
index++;
}
NSPredicate *matchAttributes = [NSPredicate predicateWithFormat:predicate argumentArray:predicateArguments];
--
是否有更短或更有效的方法来实现这个谓词?
请注意,由于不支持 NSFetchRequest(核心数据),因此块谓词不是一个选项
【问题讨论】:
标签: ios cocoa-touch core-data nspredicate