Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add magicalRecord to an existing project with Core Data?

I have a cocoa project that are in the late stages of development. I use Core Data and bindings.

Lately I wanted to test magicalRecord, just because it seems like it will help me to minimize a lot of cumbersome coredata code and even subclassing entities.

It seems like a straight forward implementation using cocapods.

Question

Is it a good idea to implement magicalRecord to an existing CoreData project and if so how is it best done? I'm thinking mostly about my existing store and code.

Thanks

like image 959
Mikael Avatar asked Dec 03 '22 22:12

Mikael


1 Answers

Yes. Magical Record is simplify your life! There is nothing hard to use them in already created project.

Just be very careful with contexts. MR is automatically managed, create, merge context. And when you start use them - any actions with context you should do trough Magical Record MR_ methods.


Here is a main step to configure Magical Record:

  1. Add Magical Record through CocoaPods: add to Podfile line: pod 'MagicalRecord'
    (don't forget to run pod install)
  2. setup managedObjectContext in start application:

AppDelegate.m

    -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [MagicalRecord setupCoreDataStack];
        _managedObjectContext = [NSManagedObjectContext MR_defaultContext];
        //other your code
    }

And when you want to parse JSON to Entity - write this:

    [Item MR_importFromObject:JSONToImport];

And MR_importFromObject method will automatically create new Entity or update the existing one.

Specific id for each Entity is attribute of your entity name plus "ID". (for example if Entity named "Item" - unique Attribute name would be "ItemID") or you can specify special key that named "mappedKeyName" and set your unique ID.

3. Save changes:

[_managedObjectContext MR_saveToPersistentStoreAndWait];

4. Fetch Data:

NSArray items = [Item MR_findByAttribute:@"itemID" 
                               withValue:"SomeValue" 
                              andOrderBy:sortTerm 
                               ascending:YES 
                               inContext:[NSManagedObjectContext MR_defaultContext]];

5. And finally, before your app exits, you should use the clean up method:

[MagicalRecord cleanUp];

About Multithreading Usage:

To use context in not main thread - you must create localContext in every thread.

Like this:

NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
//do thing with localContext - fetch, import, etc.

Here is very nice tutorial for MR usage: cimgf: importing-data-made-easy

like image 72
skywinder Avatar answered Dec 05 '22 10:12

skywinder