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

时间:2017-01-23 06:38:39

标签: ios core-data save parent-child

我正在使用子上下文来保存核心数据对象但它根本没有保存。代码有什么问题? 我尝试删除执行块并使用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);
            }
        }];

    }];
}

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的方法,但错误处理不是一个例子:

确保使用主要上下文正确设置您的专用队列。

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)")
    }
}

使用私人队列的正确方法

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

答案 1 :(得分:0)

我认为您的代码包含两个问题。

第一个是backgroundManagedObjectContext方法内部。 从未设置过ivar _managedObjectContext

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

第二个可能是您拨打两次performBlock

- (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
        // Comment this ->[temporaryContext performBlock:^{
            // push to parent
            NSError *errorTemp;
            if (![temporaryContext save:&errorTemp])
            {
                // handle error
                NSLog(@"Temp MOC Save Error: %@",errorTemp.description);
            }
        // Comment this -> }];

    }];
}

如果需要,请不要忘记将其保存在temporaryContext的父上下文中。