簡體   English   中英

合並托管對象上下文后,托管對象屬性變為零

[英]managed object property becomes nil after merging managed object contexts

我有一個名為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);
         }
      }];
   }
}

我無法弄清楚為什么會這樣。 但我確實找到了一個有效的解決方案。 我更改了調用setSubcategory的代碼來調用名為[SpecialItem updateSubcategory:subcategory]的新方法。

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

這修復了它,代碼已經運行了好幾個月了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM