2013-06-07 2 views
1

나는 CoreData에서 1 result 또는 nil을 기대하고 있습니다. CoreData에서 항상 NSArray를 가져 옵니까?

현재 나는이 NSArray로 가져 오기 설정하고이 IconRoutine* 객체로 가져 오기 위해 서 있지만 [context executeFetchRequest:fetchIcon error:&error];가 나는 것을 시도 할 때 따라서 충돌의 결과로, 배열로 가져 오기 위해 필요로 나는 시도했다.

은 내가 어쩌면 다른 방법으로 내가 해달라고하는 entity object에 페치 nil를 확인하기 위해 if ([Icon count] !=0)이 필요하고 난 그냥 다른 방법으로 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

WHy -1 ?? ....... –

+3

그게 바로 핵심 데이터가 작동하는 방식입니다. 나는 두려워합니다. 항상 배열로 가져옵니다. –

+6

반환 값'nil'은 "error"를 의미하는 반면, 빈 배열은 "결과 없음"을 의미합니다. –

답변

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;  
} 

이것은 분명히에만 작동합니다. lastObjectNSArray이 nil이거나 배열이 비어있는 경우 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; 
} 

희망을!

관련 문제