Aim: Gain all the speed of CoreData but with a friendly, ActiveRecord style interface.
- Add the SimpleData repository to your project
- Add all the .m files in Lib to your target
- Right click the .m file
- In the target tab, check the box for your target
- Go to File > New File then choosing Resource > Data Model
- Open the data model and edit it to your hearts desire
- Tip: you might want to create date attributes called createdAt and updatedAt as they will come on handy later
- In the data model editor, select classes you wish to use in your project
- Choose File > New File. In the New File dialog, select Managed Object Class.
- Depending on the version of Xcode you’re using, the Managed Object Class may be available in the iPhone OS section under Cocoa Touch Classes, or you may need to choose the template in the Mac OS X section, under Cocoa—either will work correctly.
- Click Next. The correct location and targets should have been selected for you. Click Next to accept them.
- You should see the Entity selection pane, with the Event entity selected. The “Generate accessors” and “Generate Objective-C 2.0 properties” options should also be selected.
- Click Finish to generate the files.
- Subclass the generated classes so the next time you auto-generate your additions are not clobbered.
You are now ready to start working with SimpleData
- First, import the SimpleStore header
- To create or open an existing database simply call:
- If you give just a filename, the simple store will be placed in the documents directory.
- To create an object:
[User createWithAttributes:attributesDict]; [User createWithName:@"Brian" email:@"firstname.lastname@example.org"]; [User createWithEmail:@"email@example.com" name:@"John"];
- To find an object:
[User findByName:@"Brian"]; [User findAll] NSArray *users = [User findAllByStarSign:@"Libra" sortBy:@"name" sortByDescending:@"createdAt"];
- To update an object:
User *u = [User findByName:@"Brian"]; u.name = @"Brian Collins"; [u save];
- Setting non object attributes (unfortunately):
[User createWithName:@"Brian" smoker:[NSNumber numberWithBool:NO]];
- Find or create an object if it doesn’t exist:
[User findOrCreateByName:@"Brian" email:@"firstname.lastname@example.org"].email; // => @"email@example.com" [User findOrCreateByName:@"Brian" email:@"firstname.lastname@example.org"].email; // => @"email@example.com" because it exists
- Build and run with the target “Test” and watch the log output
- Subclass SDTableViewController
- You may only have one SimpleStore open per thread.
- There is no validation, but the standard coredata validation should still work.
- You will get warnings unless you prototype the methods you use. See this wiki article
- SQLite Persistent Objects the same idea but for naked sqlite. More mature.