1
我在回答我自己的問題。直到我看到儘可能多的其他答案,我纔會接受。NSFetchRequest有時只返回結果
在過去的幾天我一直在掙扎與下面的代碼
- (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
,它只是在一半時間內檢索該對象。我實在無法解釋爲什麼。有任何想法嗎?