这简直让我抓狂。
我有 2 个使用 NSStrings 作为唯一属性的实体。
创建比较 NSString 的谓词的正确方法是什么?
目前我有: [NSPredicate predicateWithFormat:@"unique= %@", uniqueValue];
我感觉这是在比较指针地址,而不是实际的字符串值,但我无法证实这一点。我需要为精确的字符串匹配返回 yes。
-(BOOL)uniqueEntityExistsWithEnityName:(NSString*)entityName UniqueKey:(NSString*) uniqueKey UniqueValue:(NSString*)uniqueValue SortAttribute:(NSString*)sortDescriptorAttribute ManagedObjectContext:(NSManagedObjectContext*) context;
{
BOOL returnValue = NO;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
//what is the correct predates to compare the text an string core data property against a passed in string?
request.predicate = [NSPredicate predicateWithFormat:@"unique= %@", uniqueValue];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:sortDescriptorAttribute ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches)
{
NSLog(@"Error: no object matches");
}
else if([matches count] > 1) {
NSLog(@"Error: More than one object for unique record");
returnValue = YES;
} else if ([matches count] == 0) {
returnValue = NO;
} else {
returnValue = YES;
}
return returnValue;
}
最佳答案
就编码而言,单个等号甚至不是比较器。
我假设 unique 是一个 NSManagedObject 属性。
[NSPredicate predicateWithFormat:@"unique LIKE %@", uniqueValue];
请注意,这是区分大小写的。如果你想让它变得不敏感,那么你可以在 LIKE 后面加上 [c]。
关于objective-c - iOS Core Data 如何使用谓词正确比较字符串文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9825088/