Preface
Coredata is a frequently used data persistence Technology in iOS development. However, the operation process is a little complicated. Even if you only implement simple access and do not involve request optimization, you also need to perform a lot of configuration work. The amount of code is usually dozens of lines, it also takes a lot of time for new users.
Magicalrecord is a library of OC to facilitate coredata. It absorbs the active record mode of Ruby on Rails with the goal:
- Simplify core data-related code
- Clear, simple, and single-row Access Allowed
- You can still modify nsfetchrequest when you need to optimize the request.
Install
1. Download magicalrecord from GitHub
2. After the download is complete, drag the magicalrecord folder to xcode and add it to the project. Add coredata framework.
3. AddCoredata + magicalrecord. h
4,Option:If you do not want to includeMr _Prefix, e.g. used directlyFindallReplaceMr_findallIn PCHCoredata + magicalrecord. hPreviously added# Defin mr_shorthandYou can.
Environment requirements
Environment required by magicalrecord:
- IOS 5.x and later, Mac OS 10.7 and later
- Arc
Ios4, no arc, compatible version, 1.8.3
Create a model
Create a model. xcdatamodeld, add a person entity, and add the age firstname lastname attributes. Last useEditor> Create nsmanagedobject subclassOrm generates the person class.
Initialization
In appdelegate:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{ [MagicalRecord setupCoreDataStackWithStoreNamed:@"Model.sqlite"]; // ... return YES;}- (void)applicationWillTerminate:(NSNotification *)aNotification{ [MagicalRecord cleanUp];}
Initialization is completed !!
Add
Person *person = [Person MR_createEntity];person.firstname = @"Frank";person.lastname = @"Zhang";person.age = @26;[[NSManagedObjectContext MR_defaultContext] MR_save];
Query
// Find all persons in the database. Nsarray * persons = [person mr_findall]; // query all persons and sort them by first name. Nsarray * personssorted = [person mr_findallsortedby: @ "firstname" ascending: Yes]; // query all person records whose age attribute is 25. Nsarray * personsageeuqals25 = [person mr_findbyattribute: @ "Age" withvalue: [nsnumber numberwithint: 25]; // find the first record in the database: person * person = [person mr_findfirst];
Change
Person * person =...; // here, person. lastname = object; [[nsmanagedobjectcontext mr_defaultcontext] mr_save];
Delete
Person * person =...; // [person mr_deleteentity] here; [nsmanagedobjectcontext mr_defaultcontext] mr_save];
More
- Magicalrecord official
- Magical record getting started
- Using coredata with magicalrecord
- Magical record: How to make programming with core data pleasant
From: http://www.cnblogs.com/mybkn/p/3328183.html
Coredata Data Storage