Ale*_*one 6 core-data objective-c nsstring nspredicate ios
这实际上让我疯狂.
我有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;
}
Run Code Online (Sandbox Code Playgroud)
在编码方面,单个等号甚至不是比较器.
我将假设unique是一个NSManagedObject属性.
[NSPredicate predicateWithFormat:@"unique LIKE %@", uniqueValue];
Run Code Online (Sandbox Code Playgroud)
请注意,这是区分大小写的.如果你想让它变得不敏感,那么你可以在LIKE之后放[c].
我没有看到你的谓词有问题.=如果你想匹配完全的字符串,单个是完美的.如果您不需要通配符匹配,则不需要较慢的LIKE.(谓词格式字符串语法)
但是,您的代码中存在问题,并且可能会导致您进行不正确的假设.你的if/then/else,或者至少第一条消息是错误的.如果提取不返回数组,则意味着提取失败,并不意味着提取没有返回对象.
它应该更像是这样的:
if (!matches)
{
NSLog(@"Error: couldn't execute fetch request %@", error);
}
else if([matches count] > 1) {
NSLog(@"Error: More than one object for unique record");
returnValue = YES;
} else if ([matches count] == 0) {
NSLog(@"couldn't match objects");
returnValue = NO;
} else {
// [matches count] == 1
NSLog(@"matched one object");
returnValue = YES;
}
Run Code Online (Sandbox Code Playgroud)
哦,我会改变条件的顺序.在我看来,像(!匹配),([匹配计数] == 1),([匹配计数] == 0),(其他)这样的结构更有意义,而且更容易阅读.你把最重要的(因为这是你真正想要的)条件放在最后的"匿名"中.
| 归档时间: |
|
| 查看次数: |
12635 次 |
| 最近记录: |