我在覈心數據這一基本一個一對多的關係:核心數據。因之取同一對象上返回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)而多次被調用。
的行爲是這樣的:
- 第一次被調用,品牌能夠正確讀取,並通過這個函數返回。
- 第二次(和以下次數),對於以前的品牌,該函數返回零。
有誰注意到我究竟做錯了什麼?
的NSLog(@「擷取的對象:%@錯誤說明:%@」,fectchedObjects,[錯誤localizedDescription]) ;之前把這個for循環和調試 – 0x8badf00d 2011-12-24 15:17:14
擷取的對象:( )錯誤說明:(空) – luli2it 2011-12-24 15:24:23