我从CoreData
获取某些内容,我期待1 result
或nil
。
目前我将fetch设置为NSArray
并试图获取IconRoutine*
对象,但[context executeFetchRequest:fetchIcon error:&error];
需要获取数组,从而导致崩溃我试过的时候。
我想我想知道的是,如果我可以通过其他方式获取entity object
,那么我就不需要if ( [Icon count] !=0 )
来检查nil
而我可以返回获取的内容并在另一种方法中处理nil entity
。
或者可能只是一种更有效的方式(如果有的话)来处理您期望1
或nil
的结果。
- (IconRoutine *) getIconRoutine {
NSFetchRequest *fetchIcon = [[NSFetchRequest alloc] init];
NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"IconRoutine" inManagedObjectContext:context];
[fetchIcon setEntity:entityItem];
[fetchIcon setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"User",@"Routine", nil]];
[fetchIcon setPredicate:[NSPredicate predicateWithFormat:@"(routine.routineName == %@) AND (user.email LIKE %@) AND (author LIKE %@)",_routineNameInput.text,_appDelegate.currentUser,_routineAuthor]];
NSError *error = nil;
NSArray* Icon = [context executeFetchRequest:fetchIcon error:&error];
if ( [Icon count] !=0 ) {
return Icon[0];
}
return NO;
}
答案 0 :(得分:1)
这是一个选项。不一定是您正在寻找的解决方案,但可能有所帮助:
- (IconRoutine *) getIconRoutine {
NSFetchRequest *fetchIcon = [[NSFetchRequest alloc] init];
NSEntityDescription *entityItem = [NSEntityDescription entityForName:@"IconRoutine" inManagedObjectContext:context];
[fetchIcon setEntity:entityItem];
[fetchIcon setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObjects:@"User",@"Routine", nil]];
[fetchIcon setPredicate:[NSPredicate predicateWithFormat:@"(routine.routineName == %@) AND (user.email LIKE %@) AND (author LIKE %@)",_routineNameInput.text,_appDelegate.currentUser,_routineAuthor]];
return [context executeFetchRequest:fetchIcon error:nil].lastObject;
}
这显然只有在您不关心错误消息时才有效。如果lastObject
为nil或者数组为空(NSArray
,那么indexOutOfBoundsException
将返回nil!否则,它将返回最后一个对象,如果只有一个,它将返回该对象。
如果你关心错误,你可以简单地做:
- (IconRoutine *) getIconRoutine {
// fetch code from above
// ..
NSError *fetchError
IconRoutine *result = [context executeFetchRequest:fetchIcon error:&fetchError].lastObject;
if (fetchError) {
// handle the error
}
// return whatever result is anyway because if there was an error it would already be nil, and if not then it is the object you are looking for
return result;
}
希望这有帮助!