是否可以在Core Data中进行不区分大小写的提取?

时间:2016-03-10 16:29:56

标签: ios objective-c macos core-data nspredicate

我正在尝试在NSManagedObjectContenxt上执行获取请求,并且我希望谓词不区分大小写。

我尝试了几个我找到的解决方案,但它们只适用于NSArray(filteredArrayUsingPredicate),但不适用于Core Data。

例如:

我的持久存储包含一个NSManagedObject,' Car',其属性为' name'它的价值是" GMC"。

1)以下返回一个空数组:

NSFetchRequest* fetch = [[NSFetchRequest alloc] init];
fetch.entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:moc];

fetch.predicate = [NSPredicate predicateWithFormat:@"name matches[c] %@", @"gmc"];

NSArray* cars = [moc executeFetchRequest:fetch error:nil];

2)以下与' EXC_BAD_ACCESS'发生了冲突:

fetch.predicate = [NSPredicate predicateWithFormat:@"name ==[c] %@", @"gmc"];

NSArray* cars = [moc executeFetchRequest:fetch error:nil];

3)唯一有效的提取是:

fetch.predicate = [NSPredicate predicateWithFormat:@"name == %@", @"GMC"];

NSArray* cars = [moc executeFetchRequest:fetch error:nil];

是否可以在Core Data中进行不区分大小写的提取?怎么样?

感谢。

3 个答案:

答案 0 :(得分:1)

尝试以下代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UPC ==[c] %@ OR ItemID ==[c] %@", aUPCCode,aUPCCode];

答案 1 :(得分:0)

关键字"喜欢"和"包含"似乎工作得很好。

fetch.predicate = [NSPredicate predicateWithFormat:@"name like[c] %@", @"gmc"];

fetch.predicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", @"gmc"];

可在此处找到更多关键字选项和详细信息: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-CJBDBHCB

在这里 http://nshipster.com/nspredicate/

答案 2 :(得分:0)

将@selector(caseInsensitiveCompare :)与fetchRequest一起使用,如:

NSSortDescriptor *sortDescr = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Car"];
[fetchRequest setSortDescriptors:@[sortDescr]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name matches[c] %@", @"gmc"]];

然后像往常一样进行提取。