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

I have a cocoa project that is in the late stages of development. I use basic data and bindings.

I recently wanted to test magicalRecord, just because it looks like it will help me minimize a lot of cumbersome coredata code and even subclass objects.

Looks like direct execution using cocapods.

Question

It is a good idea to implement magicalRecord for an existing CoreData project, and if so, how to do it? I think mainly about my existing store and code.

thanks

+4
source share
1 answer

Yes. Magical Record makes your life easier! An already created project has nothing difficult to use.

Just be very careful with contexts. MR is automatically controlled, creates, combines the context. And when you start using them - any actions with a context that you must perform using the Magic Record MR_ methods.


Here is the basic step for setting up Magical Record:

  • Add magic entry via CocoaPods: add to subfile line: pod 'MagicalRecord'
    (don't forget to run pod install )
  • setup managedObjectContext in the startup 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 on Entity - write this:

  [Item MR_importFromObject:JSONToImport]; 

And the MR_importFromObject method will automatically create a new object or update an existing one.

The specific identifier for each object is an attribute of your object name plus "ID". (for example, if Entity with the name "Item" - the unique attribute name will be "ItemID" ), or you can specify a special key with the name "mappedKeyName" and set your unique identifier.

3. Save changes:

 [_managedObjectContext MR_saveToPersistentStoreAndWait]; 

4. Extract data:

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

5. And finally, before exiting your application, you should use the cleanup method:

 [MagicalRecord cleanUp]; 

About multithreading Usage:

To use context in a non-main thread, you must create a localContext in each thread.

Like this:

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

Here is a very good tutorial on using MP: cimgf: import-data-made-easy

+17
source

Source: https://habr.com/ru/post/1499658/


All Articles