我的应用程序中有以下关系:
产品 ->> 产品订单 <<- 订单
然后我有两个 Obj-c 类别来建立这些关系:
产品订单+产品
+ (ProductOrder *)addProductToOrderWithProduct:(Product *)product inManagedObjectContext:(NSManagedObjectContext *)context {
ProductOrder *orderProduct = nil;
orderProduct = [NSEntityDescription insertNewObjectForEntityForName:@"ProductOrder" inManagedObjectContext:context];
NSManagedObjectID *productID = [product objectID];
orderProduct.qnty = product.qnty;
orderProduct.price = product.price;
[(Product *)[context objectWithID:productID] addOrderedProductsObject:orderProduct];
return orderProduct;
}
然后订单+产品订单
+ (Order *)addOrderedProductToOrderWithOrderedProduct:(ProductOrder *)orderedProduct inManagedObjectContext:(NSManagedObjectContext *)context {
Order *order = nil;
order = [NSEntityDescription insertNewObjectForEntityForName:@"Order" inManagedObjectContext:context];
NSManagedObjectID *orderedProductID = [orderedProduct objectID];
[order addOrderProductsObject:(ProductOrder *)[context objectWithID:orderedProductID]];
return order;
}
我将产品添加到这些关系中,如下所示:
for (Product *prod in [self.fetchedResultsController fetchedObjects]) {
[[[DataManager sharedInstance] backgroundManagedObjectContext] performBlock:^{
ProductOrder *prodOrder = [ProductOrder addProductToOrderWithProduct:prod inManagedObjectContext:[[DataManager sharedInstance] backgroundManagedObjectContext]];
Order *order = [Order addOrderedProductToOrderWithOrderedProduct:prodOrder inManagedObjectContext:[[DataManager sharedInstance] backgroundManagedObjectContext]];
NSInteger amount = [order.orderNumber integerValue];
amount++;
order.orderNumber = [NSString stringWithFormat:@"Order %@", [NSNumber numberWithInteger:amount]];
[[DataManager sharedInstance] saveBackgroundContext];
[[DataManager sharedInstance] saveMasterContext];
}];
}
我现在想将这些产品分组到标题中。我的 Order 实体中有这个 orderNumber 属性,我想为添加到关系中的每组产品递增。我将如何做到这一点?
视觉示例: