ios - 子上下文未保存在核心数据中

标签 ios core-data save parent-child

我正在使用子上下文来保存核心数据对象,但它根本没有保存。代码可能有什么问题? 我尝试通过删除执行 block 并使用 performblockAndwait 但没有工作。像 prepareDataForCustomYearlyOption 方法一样,我还有其他三种方法用于每天、每周和每月,几乎与下面的代码相同。

另一个地方可以使用相同的代码。

- (NSManagedObjectContext *)backgroundManagedObjectContext
{
    if (_managedObjectContext == nil) {
         [[OUCSCoreDataManager privateInstance]managedObjectContext];
    }
    NSManagedObjectContext *temporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    temporaryContext.parentContext = _managedObjectContext;
    return temporaryContext;
}
- (void)prepareDataForCustomYearlyOption {

    if ([CoreDataManager countForEntity:kCALENDAR_CUSTOM_YEARLY_REPEAT_OPTIONS] != 0) {
        return;
    }

    NSManagedObjectContext *temporaryContext = [[CoreDataManager privateInstance]backgroundManagedObjectContext];

    [temporaryContext performBlock:^{
        @try {
            RepeatOptionsCustomYearly *yearlyOption = [RepeatOptionsCustomYearly insertInManagedObjectContext:temporaryContext];
            yearlyOption.title = NSLocalizedString(k_Yearly, @"REPEAT_OPTIONS_TITILE3");
            yearlyOption.isSelected = [NSNumber numberWithBool:NO];
            yearlyOption.every = [NSNumber numberWithInt:1];
            yearlyOption.startOn = [NSDate date];
            yearlyOption.endsOn = [NSDate date];
            yearlyOption.neverEnds = [NSNumber numberWithBool:NO];
            yearlyOption.summary = @"";
            yearlyOption.everyRange = [NSKeyedArchiver archivedDataWithRootObject:[self getYearRange]];

        } @catch (NSException *exception) {
            NSLog(@"Calendar Manager Exception: --> %@ %@",exception.name, exception.reason);
        }
        // push to parent
        [temporaryContext performBlock:^{
            // push to parent
            NSError *errorTemp;
            if (![temporaryContext save:&errorTemp])
            {
                // handle error
                NSLog(@"Temp MOC Save Error: %@",errorTemp.description);
            }
        }];

    }];
}

最佳答案

你可以尝试这样的事情,但错误处理不是一个可以遵循的例子:

确保您的私有(private)队列在主上下文中正确设置。

func getPrivateQueueMOC() -> NSManagedObjectContext?
{
    if let moc = delegate.managedObjectContext
    {
        let privateMOC = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
        privateMOC.parent = moc
        return privateMOC
    }

    return nil
}

这可以确保您尽快保存更改并更新主上下文

func savePrivateContext(privateContext:NSManagedObjectContext)
{
    do {
        try privateContext.save()

        guard let moc = delegate.managedObjectContext else { return }
        moc.performAndWait {
            do {
                try moc.save()
            } catch {
                fatalError("Failure to save context: \(error)")
            }
        }
    } catch {
        fatalError("Failure to save context: \(error)")
    }
}

私有(private)队列的正确使用方法

func persistStuff(_ stuff:[Dictionary<String, AnyObject>])
{
    if stuff.isEmpty
    {
        return
    }

    if let context = getPrivateQueueMOC()
    {
        context.perform({ () -> Void in
            // Do your stuff here

            if context.hasChanges
            {
                self.savePrivateContext(privateContext: context)
            }

            DispatchQueue.main.async(execute: { () -> Void in
                // Tell UI to update
            })
        })
    }
}

关于ios - 子上下文未保存在核心数据中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41800539/

相关文章:

ios - 将对象从主队列中的父上下文传递到私有(private)队列中的子上下文

ios - 在 UIImageView 的图像集上设置背景图像 - Objective C

ios - 在 Ipad 上的 PowerPoint 中打开 PowerPoint 文件

ios - Xcode 6.0.1 不显示内存使用情况

ios - 在 CoreData NSSet 上使用 'filteredSetUsingPredicate' 时崩溃(NSInvalidArgumentException : set argument is not an NSSet)

c++ - 保存未知数量的 int 和 char 输入

ios - Xamarin Ios - 仅在一侧创建圆形按钮

ios - "Can' t 为源存储找到模型“核心数据错误

ios - 将对象添加到实例变量数组

emacs - 如何使 emacs 在保存时在迷你缓冲区中显示短(不完整)文件路径?