合并托管对象上下文后,托管对象属性变为零

时间:2016-06-25 16:56:27

标签: ios cocoa core-data

我有一个名为SpecialItem的托管对象,并调用setSubcategory来更改子类别。当我保存临时上下文并与主上下文合并时,以某种方式调用setSubcategory作为子类别传递nil。这通常会导致在myProperty设置为nil的情况下保存SpecialItem对象。我不知道调用setSubcategory是什么。我没有明确地调用setSubcategory:nil。

我的问题是,发生了什么以及如何解决这个问题?

这是托管对象实现:

@interface SpecialItem : GenericItem
@property (nonatomic, strong) Subcategory *subcategory;
@property (nonatomic, strong) MyProperty *myProperty;
@end

@implementation SpecialItem
@dynamic subcategory;
@dynamic myProperty;

- (void)setSubcategory:(Subcategory *)subcategory
{
   [self willChangeValueForKey:@"subcategory"];
   [self willChangeValueForKey:@"myProperty"];

   [self setPrimitiveValue:subcategory forKey:@"subcategory"];
   [self setPrimitiveValue:subcategory.category.myProperty forKey:@"myProperty"];

   [self didChangeValueForKey:@"myProperty"];
   [self didChangeValueForKey:@"subcategory"];
}
// ...

托管对象上下文的设置如下:

self.tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
self.tempContext.parentContext = self.dataManager.mainContext;

最终我有这个:

[self saveTempContext];

这是saveContext实现:

- (void)saveContext
{
   LogAndPrint(@"Before save.");
   [self.tempContext performBlockAndWait:^{
      NSError *error = nil;
      if (![self.tempContext save:&error])
      {
         LogAndPrint(@"Error occurred while saving context: %@", error);
      }
   }];

   LogAndPrint(@"Middle of save.");

   [self.dataManager.mainContext performBlockAndWait:^{
      NSError *error = nil;
      if (![self.dataManager.mainContext save:&error])
      {
         LogAndPrint(@"Error occurred while saving context: %@", error);
      }
   }];

   [self.dataManager synchronize];
   LogAndPrint(@"After save.");
}

这是同步实现:

- (void)synchronize
{
   LogAndPrint(@"Synchronizing Core Data changes.");
   if (self.persistentContext.hasChanges) {
      [self.persistentContext performBlockAndWait:^{
         NSError *error =  nil;
         if (![self.persistentContext save:&error]) {
            LogAndPrint(@"Error occurred while saving persistent context: %@", error);
         }
      }];
   }
}

1 个答案:

答案 0 :(得分:0)

我无法弄清楚为什么会这样。但我确实找到了一个有效的解决方案。我更改了调用setSubcategory的代码来调用名为[SpecialItem updateSubcategory:subcategory]的新方法。

- (void)updateSubcategory:(Subcategory *)subcategory
{
   self.subcategory = subcategory;
   self.myProperty = subcategory.category.myProperty;
}

这修复了它,代码已经运行了好几个月了。