ios / objective-c:保存核心数据时出错

时间:2015-10-19 21:52:41

标签: ios objective-c core-data

我正在尝试将从某些JSON创建的对象保存在核心数据中,而不是保存。我怀疑问题是我创建托管对象上下文太多次或尝试保存到错误的托管对象上下文。当我得到managedobjectcontext = nil错误时,我必须继续声明它。想知道是否有人可以帮助我发现我没有找到的错误。

-(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
        }

}

1 个答案:

答案 0 :(得分:0)

这里确实存在不必要的背景。应删除第8行的那个。同时检查您调用或使用MOC时是否使用了一致的名称,即&#34; * context&#34; vs.&#34; * managedobjectcontext&#34;