[英]Do I always fetch into a NSArray from CoreData?
我从CoreData
那里获取了一些1 result
,我期望1 result
或nil
。
目前,我将获取设置为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;
}
这是一个选项。 不一定是您正在寻找的解决方案,但可能会有所帮助:
- (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;
}
显然,这仅在您不关心错误消息时才有效。 如果NSArray
为nil或数组为空,则lastObject
将返回nil(因此永远不会indexOutOfBoundsException
)! 否则,它将返回最后一个对象,如果只有一个,它将返回该对象。
如果您确实关心该错误,则只需执行以下操作:
- (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;
}
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.