Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MagicalRecords persisting in background thread with image fetching?

I have the following code:

dispatch_async(dispatch_get_main_queue(), ^{
    NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread];

    Item *newItem = [Item createInContext:localContext];
    newItem.title = NULL_TO_NIL([itemJson valueForKey:@"title"]);
    newItem.image_url = NULL_TO_NIL([itemJson valueForKey:@"image_url"]);
    newItem.order_id = @([[self largestOrderId] intValue] + 1);

    NSURL *url = [NSURL URLWithString:newItem.image_url];
    NSData *data = [[NSData alloc] initWithContentsOfURL: url];
    if (data == nil) {
        NSLog(@"Image data is nil from %@", url);
    } else {
        NSLog(@"Image fetched in saveItemFromJson for cid:%@ order_id:%@", newItem.cid, newItem.order_id);
        newItem.image = [UIImage imageWithData:data];
    }

    if (![localContext hasChanges]) {
        NSLog(@"No local change detected. Quitting");
        return;
    }

    [localContext saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            NSLog(@"Item persisted for cid:%@ order_id:%@", newItem.cid, newItem.order_id);
    }];
});

I seem to be getting a lot of the following:

2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Saving <NSManagedObjectContext (0x8386a90): *** DEFAULT ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Parents? 1
2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Synchronously? 0
2013-02-13 18:55:47.497 Giordano.iPhone[13956:c07] Image fetched in saveItemFromJson for cid:7218 order_id:10
2013-02-13 18:55:47.497 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Saving <NSManagedObjectContext (0x8386a90): *** DEFAULT ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.498 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Parents? 1
2013-02-13 18:55:47.498 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Synchronously? 0
2013-02-13 18:55:47.499 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x8386a90) Context DEFAULT is about to save. Obtaining permanent IDs for new 10 inserted objects
2013-02-13 18:55:47.501 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Saving <NSManagedObjectContext (0x8385aa0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Save Parents? 0
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Save Synchronously? 1
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x8385aa0) Context BACKGROUND SAVING (ROOT) is about to save. Obtaining permanent IDs for new 10 inserted objects
2013-02-13 18:55:47.505 Giordano.iPhone[13956:c07] __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x8385aa0) → Finished saving: <NSManagedObjectContext (0x8385aa0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.505 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING

With the following error messages:

2013-02-13 18:55:47.511 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.513 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING


2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)
2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)
2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)

I am avoiding to use saveInBackgroundWithBlock because it's being deprecated (docs needs to be updated?)

Any ideas with what's wrong with my code?

UPDATE

My team has decided that MagicalRecord is too buggy for now. We have completely migrated our code out of MR back to CoreData. Thanks for your attention.

like image 492
disappearedng Avatar asked Oct 06 '22 00:10

disappearedng


2 Answers

I had the same issue! It was fixed only when I did saving context by my self manually without MR.

here is my solution:

NSManagedObject+MyCategory.h

+ (void)saveDataInBackgroundWithBlock:(void(^)(NSManagedObjectContext *localContext))saveBlock
                           completion:(void(^)(void))completion;

+ (NSManagedObjectContext *)newMergableBackgroundThreadContext;

- (void)saveWithCompletion:(void(^)(void))completion;

.m

+ (NSManagedObjectContext *)newMergableBackgroundThreadContext {
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    context.parentContext = [self mainThreadContext];
    [context.userInfo setObject:[NSNumber numberWithInteger:VKCoreDataManagedObjectContextIDTempBackground]
                         forKey:@"contextID"];
    [context.userInfo setObject:kVKCoreDataManagedObjectContextBackgroundTemp
                         forKey:@"contextDebugName"];
    VKDLog(@"* New mergable backround context created! *");
    return context;
}

+ (void)saveDataInBackgroundWithBlock:(void (^)(NSManagedObjectContext *))saveBlock completion:(void (^)(void))completion {
    NSManagedObjectContext *tempContext = [self newMergableBackgroundThreadContext];
    [tempContext performBlock:^{

        if (saveBlock) {
            saveBlock(tempContext);
        }

        if ([tempContext hasChanges]) {
            [tempContext saveWithCompletion:completion];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion();
                }
            });
        }
    }];
}

- (void)saveWithCompletion:(void(^)(void))completion {
    [self performBlock:^{
        NSError *error = nil;
        if ([self save:&error]) {
            NSNumber *contextID = [self.userInfo objectForKey:@"contextID"];
            if (contextID.integerValue == VKCoreDataManagedObjectContextIDMainThread) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion();
                    }
                });
            }
            [[self class] logContextSaved:self];
            if (self.parentContext) {
                [self.parentContext saveWithCompletion:completion];
            }
        } else {
            [VKCoreData handleError:error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion();
                }
            });
        }
    }];
}

and here is using sample:

[NSManagedObjectContext saveDataInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
// do your stuff with local context
} completion:^{
// handle completion, update UI or something
}];
like image 135
iiFreeman Avatar answered Oct 10 '22 03:10

iiFreeman


I had similar problems using MR a few weeks ago. In the end I decided to ditch it and do everything myself. Not really a solution to your problem, but the reasoning behind me dropping it is sound. You probably need to go and look at the actual source for MR. A large portion of the documentation is incorrect, and a fair amount of the library can only be learned by reading the source. There is most likely an issue with trying to do background processing with MR.

If your code is for iOS6+, then you should just use the Master-Main-Child Context setup. Using dispatch_async is probably a problem as well. Letting Core Data manage your threading by using the [NSManagedContext performBlock:] method is probably a whole world safer.

If you are using iOS5 or lower, the Child context and performBlock: code does not work. The easiest solution is to keep Core Data out of your threads. Pull any needed information from Core Data before entering the new thread/block. Pass that data into your block and perform any necessary processing. Then return it to your main thread in a dictionary/object of some sort, and perform your Core Data saves there.

Also a side note, i ran into this issue because of downloading images and saving them to Core Data as well, you might want to look at these questions I asked/solved in the last few weeks related to that. Might save you pulling some hair out later:

Can I access the files used for external binary storage in Core Data?

Which eventually lead me using my own storage mechanism instead of Core Data for files, and which eventually lead me to this problem/solution:

Files are no longer readable after updating application to newest version

like image 26
G. Shearer Avatar answered Oct 10 '22 03:10

G. Shearer