这实际上让我疯狂.
我有2个实体使用NSStrings作为唯一属性.
创建比较NSStrings的谓词的正确方法是什么?
目前我有:
[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].