2016-06-25 4 views
1

私はSpecialItemという名前の管理対象オブジェクトを持ち、setSubcategoryを呼び出してサブカテゴリを変更します。一時的なコンテキストを保存してメインコンテキストとマージすると、何とかsetSubcategoryがサブカテゴリとしてnilで渡されます。これにより、SpecialItemオブジェクトがmyPropertyをnilに設定して保存されることがよくあります。私はsetSubcategoryを呼び出すのか分かりません。私はsetSubcategory:nilを明示的に呼び出すわけではありません。管理対象オブジェクトのプロパティをマージした後、管理オブジェクトのプロパティが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 saveTempContext]; 

ここsaveContextは次のとおりです。

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

は最終的に私はこれを持っています実装:

ここでは
- (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); 
     } 
     }]; 
    } 
} 

答えて

0

私はこれが起こった理由を把握することができませんでした。しかし、私は解決した解決策を見つけました。 setSubcategoryを呼び出すコードを変更して、[SpecialItem updateSubcategory:subcategory]という名前の新しいメソッドを呼び出しました。

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

これは修正され、コードは数か月間うまく機能しています。

関連する問題