如何将 saveWithBlock 中的实体传递给完成块

How to pass entity in saveWithBlock to completion block

我知道 MagicalRecord 将在后端线程上执行 saveWithBlock 并在主线程上执行 completion,但只是对如何将 saveWithBlock 中的实体传递到完成块感到困惑,具体来说:

Event *wantToCreateEvent = nil;
Event *wantToUpdateEvent = toBeUpdatedEvent;

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    wantToCreateEvent = [Event MR_createEntityInContext:localContext];

    Event *localContextEvent = [wantToUpdateEvent MR_inContext:localContext];
    localContextEvent.attri = @"newValue"
} completion:^(BOOL success, NSError *error) {

    // Can I use wantToCreateEvent directly here?

    // Is wantToUpdateEvent updated here?
}

如果需要从块中修改变量,请对变量使用 __block 存储类型修饰符。

__block Event *wantToCreateEvent = nil;
__block Event *wantToUpdateEvent = toBeUpdatedEvent;

根据Apple的文档发现here:

Use __block Variables to Share Storage

If you need to be able to change the value of a captured variable from within a block, you can use the __block storage type modifier on the original variable declaration. This means that the variable lives in storage that is shared between the lexical scope of the original variable and any blocks declared within that scope.

对于实体创建,您可以使用 Megical Record 的 2 个功能

+ (id) MR_createEntityInContext:(NSManagedObjectContext *)context;
+ (id) MR_createEntity;

注意:要保存实体,您只需保存创建这些实体的上下文

后台保存

+ (void) saveWithBlock:(void(^)(NSManagedObjectContext *localContext))block;
+ (void) saveWithBlock:(void(^)(NSManagedObjectContext *localContext))block completion:(MRSaveCompletionHandler)completion;

在主线程中保存

+ (void) saveWithBlockAndWait:(void(^)(NSManagedObjectContext *localContext))block;

为了更多地了解 CoreData 和 MegicalRecord,我建议您阅读本教程

Understanding CoreData With Magical Record