2014-06-11 93 views
1

我在回答我自己的問題。直到我看到儘可能多的其他答案,我纔會接受。NSFetchRequest有時只返回結果

在過去的幾天我一直在掙扎與下面的代碼

- (id)fetchUniqueEntity:(Class)entityClass 
       withValue:(id)value 
      fromContext:(NSManagedObjectContext *)context 
      insertIfNil:(BOOL)insertIfNil { 
    if(!value) { 
     return nil; 
    } 

    NSString *entityUniqueIdentifierKey = [entityClass performSelector:@selector(uniqueIdentifierKey)]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value]; 

    NSArray *entities = [self fetchEntities:entityClass 
           withPredicate:predicate 
           fromContext:context]; 

    if(!entities || [entities count] == 0) { 
     if (insertIfNil) { 
      return [entityClass performSelector:@selector(insertInManagedObjectContext:) 
            withObject:context]; 
     } 
    } else { 
     return [entities objectAtIndex:0]; 
    } 

    return nil; 
} 

- (NSArray *)fetchEntities:(Class)entityClass 
      withPredicate:(NSPredicate *)predicate 
       fromContext:(NSManagedObjectContext *)context { 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSString *entityName = [entityClass performSelector:@selector(entityName)]; 
    [request setEntity:[NSEntityDescription entityForName:entityName 
            inManagedObjectContext:context]]; 
    if(predicate) { 
     [request setPredicate:predicate]; 
    } 

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

    if(error) { 
     NSLog(@"Error executing fetch request for %@! \n\n%@", entityName, error); 
    } 

    return entities; 
} 

頂部的輔助方法是爲了幫助一個大的下載過程中建立關係。我遇到的問題是,即使在持久性存儲(已確認)中存在一個Account對象,accountId1,它只是在一半時間內檢索該對象。我實在無法解釋爲什麼。有任何想法嗎?

回答

1

多的調試和試錯後,我發現,從

[NSPredicate predicateWithFormat:@"%K == %@", entityUniqueIdentifierKey, value]; 

改變謂詞格式

[NSPredicate predicateWithFormat:@"%K == %d", entityUniqueIdentifierKey, [value intValue]]; 

解決了這個問題。在研究了蘋果文檔後,看起來%@應該可以工作。所以我不是100%肯定爲什麼這解決了這個問題。