我有一个处于开发后期的可可项目。我使用核心数据和绑定。
最近我想测试magicRecord,只是因为它似乎可以帮助我减少很多繁琐的coredata代码甚至子类化实体。
这似乎是一个使用 cocapods 的直接实现。
问题
将magicRecord 实施到现有的CoreData 项目是否是一个好主意,如果是这样,如何最好地完成?我主要考虑我现有的商店和代码。
谢谢
我有一个处于开发后期的可可项目。我使用核心数据和绑定。
最近我想测试magicRecord,只是因为它似乎可以帮助我减少很多繁琐的coredata代码甚至子类化实体。
这似乎是一个使用 cocapods 的直接实现。
问题
将magicRecord 实施到现有的CoreData 项目是否是一个好主意,如果是这样,如何最好地完成?我主要考虑我现有的商店和代码。
谢谢
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.
pod 'MagicalRecord'
pod install
)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];
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