MagicalRecord 2.3.0/3.0 在对象中保存对象

MagicalRecord 2.3.0/3.0 saving objects within objects

我试图解决这个问题,但我找不到解决这个问题的方法。我不明白如何在新版本的 magicalrecord (MagicalRecord Docu) 中保存对象中的对象。

我有两个相互指向的对象。什么是最好的方法?

之前我可以轻松:

//create both entities
myObject = [MyObject createEntity];
subObject = [SubObject createEntity];

//connect them
myObject.subObject = subObject;

//save everything
[MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:nil];

我现在该怎么办?我试过了(根据文档):

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
    myObject = [MyObject createEntityInContext:localContext];
    subObject = [SubObject createEntityInContext:localContext];
    myObject.subObject = subObject;
} completion:^(BOOL success, NSError *error) {
    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

但这行不通:((这一切都发生在一个块中。)我很高兴收到任何建议。也许有更好或更优雅的方法。

你可以这样做:

- (void) myProcessWithContext:(NSManagedObjectContext *otherContext) {
     MyObject *myObject = [MyObject createEntityInContext:otherContext];
     SubObject *subObject = [SubObject createEntityInContext:otherContext];

     myObject.subObject = subObject;

     [otherContext saveToPersistentStoreWithCompletion::^(BOOL success, NSError *error) {
          [application endBackgroundTask:bgTask];
          bgTask = UIBackgroundTaskInvalid;
     }];
}

您仍然可以使用默认上下文:

- (void) myProcess {
     MyObject *myObject = [MyObject createEntity];
     SubObject *subObject = [SubObject createEntity];

     myObject.subObject = subObject;

     [[NSManagedObjectContext defaultContext] saveToPersistentStoreWithCompletion::^(BOOL success, NSError *error) {
          [application endBackgroundTask:bgTask];
          bgTask = UIBackgroundTaskInvalid;
     }];
}