- (IBAction)add:(id)sender
{
Artist *artist = [Artist MR_createEntity];
artist.title = @"Eminem";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
// here a large calculation
Album *album = [Album MR_createEntity];
album.title = @"Album 1";
[artist setAlbums:[NSSet setWithArray:@[album]]];
dispatch_async(dispatch_get_main_queue(),^{
[artist.managedObjectContext MR_saveToPersistentStoreAndWait];
});
});
}
MagicalRecordTest[2008:1803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'albums' between objects in different contexts (source = <Artist: 0x15eaa2d0>
/* For all background saving operations. These calls will be sent to a different thread/queue.
*/
+ (void) saveWithBlock:(void(^)(NSManagedObjectContext *localContext))block;
+ (void) saveWithBlock:(void(^)(NSManagedObjectContext *localContext))block completion:(MRSaveCompletionHandler)completion;
/* For saving on the current thread as the caller, only with a seperate context. Useful when you're managing your own threads/queues and need a serial call to create or change data
*/
+ (void) saveWithBlockAndWait:(void(^)(NSManagedObjectContext *localContext))block;
/*
If you want to reuse the context on the current thread, use these methods.
*/
+ (void) saveUsingCurrentThreadContextWithBlock:(void (^)(NSManagedObjectContext *localContext))block completion:(MRSaveCompletionHandler)completion;
+ (void) saveUsingCurrentThreadContextWithBlockAndWait:(void (^)(NSManagedObjectContext *localContext))block;
//пишу по памяти, могу где-то ошибиться
[MagicRecord saveWithBlock:^(NSManagedObjectContext *localContext){
Artist *artist = [Artist createInContext: localContext];
artist.title = @"Eminem";
Album *album = [Album createInContext: localContext];
album.title = @"Album 1";
[artist addAlbumObject:album]; //этот метод, или подобный ему должен автоматически сгенерироваться если Вы правильно генерируете классы Artist|album
}];