[英]ios/objective-c: Error saving in core data
I am trying to save an object created from some JSON in core data and it is not saving. 我正在尝试将通过JSON创建的对象保存在核心数据中,但未保存。 I suspect the problem is that I am creating the managed object context too many times or trying to save to the wrong managed object context.
我怀疑问题是我创建了太多次托管对象上下文或试图保存到错误的托管对象上下文。 I have to keep declaring it as I was getting managedobjectcontext = nil errors.
我必须不断声明它,因为我收到ManagedObjectcontext = nil错误。 Wondering if anyone could help me spot bug which has eluded me.
想知道是否有人可以帮助我发现我难以捉摸的错误。
-(void) importItems:(NSArray *)ItemsToImport
{
int i;
int max = [itemsToImport count];
IDItemServer *importItem;//this is import object
Items *Item; //this is core data entity
NSManagedObjectContext *context = self.managedObjectContext;
for (i=0;i<max;i++)
{
NSLog(@"value of i is%d:",i);
importItem = ItemsToImport[i];
NSString *name = importItem.name;
NSString *sub = importItem.sub;
//save our new and updated changes to the Core Data store
NSManagedObjectContext *context = [IDModel sharedInstance].managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:context];
//was self.managedObjectContext
// Initialize Record
NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
// Populate Record
[record setValue:name forKey:@“name”];
[record setValue:sub forKey:@“s”ub];
}
// Save Record
NSError *error = nil;
NSLog(@"BEFORE SAVE”);//Logs to console
if ([context save:&error]) {
NSLog(@"AFTER SAVE”);//does not log to console
} else {
if (error) {
NSLog(@"%@, %@", error, error.localizedDescription);//does not log to console
}
// Show Alert View
[[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your Item could not be saved." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
//THIS ALERT FIRES
}
}
There was indeed an unnecessary context here. 确实这里有不必要的上下文。 The one on line 8 should be deleted.
第8行的那个应该被删除。 Also check that whenever you invoke or use a MOC you are using a consistent name ie "* context" vs. "* managedobjectcontext"
还要检查每当您调用或使用MOC时,是否使用一致的名称,即“ * context”与“ * managedobjectcontext”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.