Updated to work with newest MagicalRecord version, as of April 13th 2013
So I have used CoreData before in my iOS applications, but until now I’ve always sticked to Apple’s CoreData Template Project. Yesterday I came across the MagicalRecord project on GitHub which promises a cleaner and simpler approach to working with CoreData.
At first I was confused on how exactly to set up a new project with CoreData and MagicalRecord. Since there were practically no tutorials / guides on the web on how to use MagicalRecord except of course for the Repository Description, I've decided to write a easy to follow step by step guide.
- Create a new project in XCode and be sure not to check "Use Core Data"
- Download the MagicalRecord source from GitHub and add it to your project
- Add the CoreData framework to your project
- Import the MagicalRecord main header file in the projects .pch file
- In the AppDelegate's application:didFinishLaunchingWithOptions:
"Targets -> Build Phases -> Link Binary with Libraries" & then add CoreData.framework
#import "MagicalRecord.h"
Call following method to setup CoreData and MagicalRecord ... see the MagicalRecord GitHub page for more setup possibilities.
[MagicalRecord setupAutoMigratingCoreDataStack];
Well that was the basic setup, easy right? Now on to the important stuff...
Create
Person *alex = [Person MR_createEntity];
alex.name = @"Alex";
alex.age = @23;
Select
//Retrieve all for aNSManagedObject subclass
NSArray *people = [Person MR_findAll];
//Retrieve first record
Person *aPerson = [Person MR_findFirst];
//Retrieve records conditionally & sort
NSArray *people = [Person MR_findByAttribute:@"name" withValue:@"alex" andOrderBy:@"age" ascending:YES];
Update
//Updating a retrieved entity is as easy as manipulating it's properties
aPerson.age = @56;
Delete
//Remove all records
[Person MR_truncateAll];
//Delete single record, after retrieving it
[alex MR_deleteEntity];
Save
//For any entities to actually be saved / updated / deleted on disk call following method
[[NSManagedObjectContext MR_defaultContext] saveToPersistentStoreAndWait];
//Again check the MagicalRecord repo for more save options
Misc
//If you want to omit the "MR_" prefix to all MagicalRecord realted method calls define following before importing the MagicalRecord header
#define MR_SHORTHAND
//Turn off MagicalRecord logging, again by defining following before header import
#define MR_ENABLE_ACTIVE_RECORD_LOGGING 0
Thats pretty much all there is to say about this great library, You can download the source code I created showcasing MagicalRecord integration here: