我有两个实体:产品和捆绑。每个人都有自己的班级。一个产品可以有多个捆绑。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