我在这个问题上回答了我自己的问题。在我看到尽可能多的其他答案之前,我不会接受它。
在过去的几天里,我一直在努力使用以下代码
- (id)fetchUniqueEntity:(Class)entityClass
withValue:(id)value
fromContext:(NSManagedObjectContext *)context
insertIfNil:(BOOL)insertIfNil {
if(!value) {
return nil;
}
NSString *entityUniqueIdentifierKey = [entityClass performSelector:@selector(uniqueIdentifierKey)];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value];
NSArray *entities = [self fetchEntities:entityClass
withPredicate:predicate
fromContext:context];
if(!entities || [entities count] == 0) {
if (insertIfNil) {
return [entityClass performSelector:@selector(insertInManagedObjectContext:)
withObject:context];
}
} else {
return [entities objectAtIndex:0];
}
return nil;
}
- (NSArray *)fetchEntities:(Class)entityClass
withPredicate:(NSPredicate *)predicate
fromContext:(NSManagedObjectContext *)context {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSString *entityName = [entityClass performSelector:@selector(entityName)];
[request setEntity:[NSEntityDescription entityForName:entityName
inManagedObjectContext:context]];
if(predicate) {
[request setPredicate:predicate];
}
NSError *error;
NSArray *entities = [context executeFetchRequest:request
error:&error];
if(error) {
NSLog(@"Error executing fetch request for %@! \n\n%@", entityName, error);
}
return entities;
}
顶级助手方法旨在帮助在大型下载期间建立关系。我遇到的问题是,即使在持久性存储中有一个Account
accountId
1
的对象(已确认),它只检索到该对象的一半时间。我老实说无法解释原因。有什么想法吗?
答案 0 :(得分:1)
经过大量调试和反复试验后,我发现从
更改谓词格式[NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value];
到
[NSPredicate predicateWithFormat:@"%K == %d", entityUniqueIdentifierKey, [value intValue]];
解决了这个问题。在研究了苹果文档之后,似乎%@
应该可行。所以我不能100%确定为什么这样才能解决问题。