的背景:
- 我正在使用库存管理应用程序。
- 用户可以将库存添加到卡车
- 添加已经在卡车上的物品时,我只想更新其数量而不是再次添加。
- 这是一对一的关系。目前只有一辆“卡车”
流程逻辑:输入项目编号后,在Items下查找它。如果找到,则创建适当的truckItem托管对象并将其保存在字典中。一旦我准备好保存对所有存储的truckInventory对象的上下文检查。如果 item 已经存在,则获取truckItem托管对象,并添加数量,销毁新创建的truckItem。节省。
问题:当检查存储的 truckItems 时,它将加载所有信息,但 item 将设置为 nil。(注意,是 nil,不是 )。因此,数量反映了正确的价值,但我们不再有合适的项目。
简化代码: 加载库存:
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"TruckItems"];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:@"item" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sort]];
loadedInventoryResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self->context sectionNameKeyPath:nil cacheName:nil];
if(![loadedInventoryResultsController performFetch:&error]) {
NSLog(@"Error! %@", [error localizedDescription]);
}
检查保存的库存简化代码:
for(NSString *mpn in items) {
TruckItems *item = [items objectForKey:mpn];
//This shows the right number of managedObjects, but the ones that are repeated show item = nil;
NSLog(@"Logged: %@", [loadedInventoryResultsController fetchedObjects]);
//Check to see if items are already in inventory. If they are update their quantities rather than adding them again.
for(TruckItems *loadedItem in [loadedInventoryResultsController fetchedObjects]) {
Items *storedItem = [loadedItem item]; //I am doing this just for testing: This comes back as nil. This is the problem as it comes nil
Items *scanned = [item item]; //Same here.
if([stored.manufacturerProductNumber isEqualToString:scanned.manufacturerProductNumber]) {
item.quantity = [loadedItem.quantity decimalNumberByAdding:item.quantity];
[context deleteObject:loadedItem];
}
}
}
//Save context
问题:为什么它被设置为零?如何避免?
提前致谢。