[英]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.