MagicalRecord 2.3.0 / 3.0保存对象内的对象

时间:2015-07-17 10:25:45

标签: ios core-data magicalrecord

我试图搞清楚,但我找不到解决这个问题的方法。我不明白如何在新版本的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;
}];

但这不起作用:((这一切都发生在一个街区。)我很高兴任何建议。也许有更好或更优雅的方式。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

- (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;
     }];
}