问题描述
|
我正在尝试从不在给定集中的核心数据中获取对象,但是我无法使其正常工作。
例如,假设我们有一个名为User的核心数据实体,它具有一些属性,例如userName,familyName,givenName和active。给定一个代表一组用户名的字符串数组,我们可以轻松获取与该用户名列表相对应的所有用户:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@\"User\"
inManagedObjectContext:moc];
[request setEntity:entity];
NSArray *userNames = [NSArray arrayWithObjects:@\"user1\",@\"user2\",@\"user3\",nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"userName IN %@\",userNames];
[request setPredicate:predicate];
NSArray *users = [moc executeFetchRequest:request error:nil];
但是,我想获取该集合的补充,即我希望核心数据中的所有用户都没有在userNames数组中指定的用户名。有谁知道如何解决这个问题?我认为在谓词(i.e.,\"userName NOT IN %@\")
中添加\"NOT\"
就足够简单了,但是Xcode抛出一个异常,称无法解析谓词格式。我也尝试过使用可用于获取请求的谓词生成器,但没有运气。该文档也不是特别有用。有什么建议吗?注释?感谢你的帮助 :)
解决方法
为了找到不在数组中的对象,您要做的就是这样:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@\"NOT (userName IN %@)\",userNames];
那应该返回所有对象的请求,而不包含您指定的对象
, 我不擅长核心数据/目标-c,但谓词应类似于以下语句;
[predicateFormat appendFormat:@\"not (some_field_name in {\'A\',\'B\',\'C\'})\"];
一个例子:
NSMutableString * mutableStr = [[NSMutableString alloc] init];
//prepare filter statement
for (SomeEntity * e in self.someArray) {
[mutableStr appendFormat:@\"\'%@\',\",e.key];
}
//excluded objects exist
if (![mutableStr isEqual:@\"\"])
{
//remove last comma from mutable string
mutableStr = [[mutableStr substringToIndex:mutableStr.length-1] copy];
[predicateFormat appendFormat:@\"not (key in {%@})\",mutableStr];
}
//...
//use this predicate in NSFetchRequest
//fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateFormat];
//...
, 这是另一个有用的示例,显示了如何获取字符串列表,并过滤掉任何不以字母A-Z开头的字符串:
NSArray* listOfCompanies = [NSArray arrayWithObjects:@\"123 Hello\",@\"-30\'c in Norway\",@\"ABC Ltd\",@\"British Rail\",@\"Daily Mail\" @\"Zylophones Inc.\",nil];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@\"NOT (SELF MATCHES[c] \'^[A-Za-z].*\')\"];
NSArray *filteredList = [listOfCompanies filteredArrayUsingPredicate:bPredicate];
for (NSString* oneCompany in filteredList)
NSLog(@\"%@\",oneCompany);
当我用A-Z索引填充UITableView
时,我会使用这种ѭ7want,并且想要不以字母开头的项目的“其他”部分。