2012-06-15 6 views
3

왜 ManagedObjects가 반환되지 않는지 알 수 있습니까? 다음 클래스에 ATNSManagedObject + EasyFetching 클래스를 추가하려고 시도하지만 가져 오기 결과가 아무 것도 반환하지 않습니다. EasyFetch 클래스 외부에서 이들을 가져 오는 경우 CoreData가 비어 있지 않다는 것을 알기 위해 100 개 이상의 객체가 있습니다.NSFetchRequest returns nothing

+ (void)deleteAllObjectsInContext; 
{ 
    NSManagedObjectContext *context = [NSManagedObjectContext defaultContext]; 
    NSEntityDescription *entity = [self entityDescriptionInContext:context]; 
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
    [request setEntity:entity]; 
    //[request setIncludesPropertyValues:NO]; 

    NSError *error = nil; 
    NSArray *results = [context executeFetchRequest:request error:&error]; 
    if (error != nil) 
    { 
     //handle errors 
     NSLog(@"delete error"); 
    } 

    for (NSManagedObject *thing in results) { <--- |results shows 0 objects| 
     [context deleteObject:thing]; 
    } 

    NSError *saveError = nil; 
    [context save:&saveError]; 
} 
+0

'NSEntityDescription * entity = [self entityDescriptionInContext : context];'는 어떻게됩니까? –

+0

결과 배열이 비어 있지 않은지 확인하십시오 (빈 배열이 아닌)? Apple에서는 오류 조건을 감지하기 위해 무 Nil 오류를 검사하는 대신 무 Nil 결과를 확인해야한다고 설명합니다. 이 해결책을 여기에 발생할 수 있지만 인식 할 수 있지만 미래에 혼란을 피할 수 있습니다 (명백하게 오류 조건이없는 경우에도 nil 않을 수 있습니다 .NSArray 대신 nil 반환 정확한 방법을 감지하는 정확한 방법입니다. 오류) –

+0

실제로 내 대답이 정확하다는 사실이 밝혀지면이 유형의 오류 검사 (Null이 아닌 오류가 아닌 결과 확인)가 도움이 될 것입니다 :-) –

답변

2

로 단순화 시도 :

// first get the context or pass it in as an argument (this is usually what I do for 
// a deleteAll class level method like this but your call 

+ (void)deleteAllObjectsInContext:(NSManagedObjectContext*)context { 

    NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@ "<yourEntity>"]; 
    // no predicate 
    // no sortDescriptors 

    NSError* error = nil; 
    NSArray* results = [context executeFetchRequest:request error:&error]; 

    if (!results || error) { // nil is an error 
     // handle error 
    } 

    // do something with results 

} 

이 방법 당신은 NSEntityDescription 개체를 검색하는 것을 방지 할 수 있습니다.

는 UPDATE :

반환 값

"수신기에서 가져와과 관련된 영구 저장의 요청에 의해 지정된 기준을 충족하는 객체의 배열 :

그냥이 passage을 추가하고 싶었 수신자의 영구 저장소 조정자 오류가 발생하면 nil을 반환하고 요청에 의해 지정된 조건과 일치하는 객체가 없으면 빈 배열을 반환합니다. "

1

귀하의 NSManagedObjectContext *context이 실제로 nil 일 가능성이 있습니다. Objective-C에서 메시지를 nil로 보내는 것은 완벽하게 받아 들일 수 있으며 문제가 어디에 있는지를 감지하기가 어려울 수 있습니다.

[NSManagedObjectContext defaultContext]에 대한 설명서를 찾을 수 없으므로 작성한 카테고리 (또는 사용하고있는 범주)라고 가정합니다. 그리고 나는 그것이 이 아니며 항상이 유효한 컨텍스트를 리턴한다고 의심합니다. 일부 로깅을 추가하고보십시오!

+0

코드를 실행하는 모든 사용자에게 샘플에서는 self.managedObjectContext 대신 _managedObjectContext를 호출하는 실수를했습니다. 후자는 기본 AppDelegate.m에 지연로드됩니다. – seo

0

이 방법을 시도하고 로그를보십시오. 현재 엔티티의 모든 것을 가져옵니다.

+ (NSArray*) retrieveEntity:(NSString*) entityName { 

// !!!Here you put your context 
NSManagedObjectContext *context = appDelegate.managedObjectContext; 

if (context == nil) { 
    NSLog(@"Error: No context"); 
    return nil; 
} 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context]; 
[fetchRequest setEntity:entity]; 

NSError *error = nil; 
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 

if (fetchedObjects == nil) { 
    // Handle the error 
    NSLog(@"Error: No fetched objects."); 
    return nil; 
} 
else 
    NSLog(@"Retrieved objects count:%d", [fetchedObjects count]); 

return fetchedObjects; 
} 

이것은 예를 들어, 호출하는 방법입니다.

// Retrieve all products 
NSArray *flXProducts = [DbConnection retrieveEntity:@"FLXProduct"]; 

0을 반환하면 데이터베이스에 문제가있는 것입니다. 데이터베이스의 SQL 파일을 찾고 터미널에서 간단한 SQL을 사용하여 문제를 나타낼 수 있습니다.