CoreData: made simple

13 May 2012

Beginning with Core Data may not be the easiest task ever. Here's the small wrapper that could make your experience a lot easier and a way more fun, especially if you're already familiar with the Active Model (Rails).

I always imainged how it would be to have the Active Model brought to the iOS. At least, the syntax is a lot more sexy than the NSManaged*'s one.

In the end, it's not hard at all. The wrapper can be found on https://github.com/supermarin/Objective-Record

Create

1
2
3
Person *john = [Person create];
john.name = @"John";
john.surname = @"Doe";

Save / Delete

1
2
john.save;
john.delete;

Find, fetch

Let's find our John

1
Person *john = [Person where:@"name == John AND surname == Doe"].first;

All the people in database:

1
2
3
for(Person *person in [Person all]) {
  NSLog(@"Person: %@", person);
}

Xcode4, new literals

When the XCode 4.4 gets released, some new Objective-C literals will come in. Then you'll be able to pass a readable dictionary(hash) in the finder method:

e.g. all the people that are 18 years old

1
NSArray *people = [Person where:@{ @"age" : @18 }];

Or a more specific one:

1
2
3
4
[Person where:@{ @"age" : @18,
                 @"member" : @YES,
                 @"state" : @"NY"
                }];

The same goes for the creation

1
Person *john = [Person create:@{ @"name" : @"John", @"age" : @12, @"member" : @NO }];

Of course, you can still use all the Core Data stuff and syntax. For some more details visit the https://github.com/supermarin/Objective-Record.