Question

I am using MagicalRecord in my iOS app, and not sure about the right way to save.

My app is about chatting, and every time the logged in user received a message, I need to update a time token.

Now I do like this:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {

    User *currentUser = [User MR_findFirstByAttribute:@"id" 
                                            withValue:@(_CURRENT_USER_ID) 
                                            inContext:localContext];

    currentUser.lastChatMessageTimeToken = [NSDate date]; 
}];

However, I believe it is not efficient because once the user logged in, his id is determined, and the currentUser is always the same.

I am thinking I should cache the currentUser as a instance variable, but cannot find corresponding MagicalRecord method to perform.

Also, I was told not to cache a NSManagedObject because it is bind to a context.

So I am not sure what I should do. Could anyone help?

Was it helpful?

Solution

You are correct in that fetching, then updating, and finally saving a single object is not very efficient. You can hold on to a reference of your currentUser object as long as you know which context to which it belongs. From there, your code will look something like this;

currentUser = //from somewhere else, a property perhaps
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext){
    User *localUser = [currentUser MR_inContext:localContext];
    localUser.lastChatMessageTime = [NSDate date];
}];

Fetching the object by object ID is going to be faster than performing a fetch request. However, since you're only changing one object, I would recommend just saving on the current thread (as long as the context is also on the correct thread):

NSManagedObjectContext *context = //....
User *currentUser = //from somewhere, and create in the context

currentUser.lastChatMessageTime = [NSDate date];

[context MR_saveToPersistentStoreAndWait];

This way there are no blocks to deal with, and you don't have to perform the save on a background queue since this single record update will likely be fast enough even on the main thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top