我有兩個實體:產品和捆綁。每個人都有自己的班級。一個產品可以有多個捆綁。iPhone - 核心數據崩潰
實體的定義是這樣的:
PRODUCTS
name, string
number, integer 16
fromBundle = to-many relationship to product
BUNDLE
name, string
number, integer 16
product = to-many relationship to fromBundle
產品被分配到捆綁這樣的:
// suppose bundle 1 is composed of products 1, 2, 3 and 4.
NSArray *myProd = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:4],
nil];
int bundleNumber = 1;
NSString *bundleName = @"My Bundle";
Bundle *aBundle = nil;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity = [NSEntityDescription entityForName:@"Bundle" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat: @"(number == %d)", bundleNumber];
NSError *error = nil;
aBundle = [[context executeFetchRequest:request error:&error] lastObject];
// as the bundle does not exist, this will run
if (!error && !aBundle) {
aBundle = [NSEntityDescription insertNewObjectForEntityForName:@"Bundle" inManagedObjectContext:context];
aBundle.string = bundleName;
aBundle.Number = [NSNumber numberWithInt:bundleNumber];
for (NSNumber *umNum in myProd) {
// the product with number = aNum is retrieved... yes it is valid at this point
Product *oneProduct = [ProductWithNumber:umNum inManagedObjectContext:context];
NSMutableSet *mutableSet = [oneProduct mutableSetValueForKey:@"fromBundle"];
[mutableSet addObject:aBundle];
}
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
// everything is fine at this point.
我現在想找回那屬於一個特定的捆綁所有產品的列表..
要做到這一點,我在捆綁類上使用此方法類
+ (NSArray *)ProductsInBundle:(Bundle*)aBundle inManagedObjectContext:(NSManagedObjectContext *)context
{
NSArray *all = nil;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity = [NSEntityDescription entityForName:@"Products" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"(fromBundle == %@)", aBundle];
NSError *error = nil;
all = [context executeFetchRequest:request error:&error]; // crashes here
return all;
}
崩潰與「一對多這裏不允許鍵」當我試圖做到這一點
NSArray *allProductsInBundle = [Bundle ProductsInBundle:aBundle inManagedObjectContext:self.managedObjectContext];
aBundle消息的最後一個方法所分配行是在這一點上有效。
「Tabuleiros」在這裏只是您的問題的複製/粘貼錯誤嗎?編輯:看起來像你已經修好它^ _^ – dontGoPlastic
只是一個錯字。 :D – SpaceDog
你是如何創建Bundle類的? (即實際的類頭和實現,你有核心數據爲你嗎?) – hypercrypt