2011-12-24 37 views
1

我在覈心數據這一基本一個一對多的關係:核心數據。因之取同一對象上返回null

  • 品牌有N個產品
  • 產品有1個品牌(反向關係到以前的)

我正在解析來自WS的產品。當產品出現時,我需要將它的品牌添加到新創建的產品中。

爲此,我需要提取品牌並將其分配給產品。

+ (Brand *) getBrandWithId : (int) brand { 
    NSManagedObjectContext * context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Brand" inManagedObjectContext:context]; 
    [fetchRequest setEntity:entity]; 
    [fetchRequest setIncludesSubentities:YES]; 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == %@", [[NSNumber numberWithInt:brand]description]]; 
    [fetchRequest setPredicate:predicate]; 

    NSError *error = nil; 
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 
    for (Brand * brand in fetchedObjects) { 
     return brand; 
    } 
    return nil; 
} 

由於一個產品接近另一個產品,因此該功能因相同品牌(同一id)而多次被調用。

的行爲是這樣的:

  • 第一次被調用,品牌能夠正確讀取,並通過這個函數返回。
  • 第二次(和以下次數),對於以前的品牌,該函數返回零。

有誰注意到我究竟做錯了什麼?

+0

的NSLog(@「擷取的對象:%@錯誤說明:%@」,fectchedObjects,[錯誤localizedDescription]) ;之前把這個for循環和調試 – 0x8badf00d 2011-12-24 15:17:14

+0

擷取的對象:( )錯誤說明:(空) – luli2it 2011-12-24 15:24:23

回答

3
NSError *error = nil; 
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 
for (Brand * brand in fetchedObjects) { 
    return brand; 
} 

此代碼看起來很奇怪。首先,你傳入一個NSError **,但忽略可能返回的錯誤。由於您的抓取似乎遇到了一些問題,因此檢查它是有意義的。

其次,for循環似乎具有誤導性。由於主體包含返回語句,因此您不能多次執行循環。雖然沒有實際的區別,似乎意圖更好的指示在這裏會是這樣的:

if (fetchedObjects != nil) { 
    return [fetchedObjects objectAtIndex:0]; 
} 
+0

謝謝迦勒。我正在檢查錯誤,我只是沒有把這部分代碼放在這裏,而不是弄得一團糟。對不起。在這種情況下,錯誤即將消失。這個問題對我來說還是沒有解決... – luli2it 2011-12-24 15:56:23

+5

答案,以防萬一有人需要知道:似乎改變%@%d是問題。這樣的效果對我來說似乎很奇怪。所以,我已經替換爲NSPredicate * predicate = [NSPredicate predicateWithFormat:@「subject_id ==%d」,brand];它的工作。感謝大家的幫助! – luli2it 2011-12-24 17:31:02

相關問題