【问题标题】:MagicalRecord 2.3.0/3.0 saving objects within objectsMagicalRecord 2.3.0/3.0 在对象内保存对象
【发布时间】:2015-07-17 10:25:45
【问题描述】:

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

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

【问题讨论】:

  • 我不知道你为什么说它不起作用。保存时会出错吗?如果有,那是什么?请检查successerror的值。

标签: ios core-data magicalrecord


【解决方案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;
     }];
}

【讨论】:

  • 谢谢。像魅力一样工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2020-08-08
  • 2015-10-15
  • 1970-01-01
相关资源
最近更新 更多