Magical Record DAO

This is magical record 2nd posts.
The first post is Magical Record First Step.

Simple Example

.xcdatamodeld

Country

  • code Integer32
  • key String

Create

-(Country *)createCountry:(int)code key:(NSString *)key {
    Country *country = [Country MR_createEntity];
    country.code = [NSNumber numberWithInt:code];
    country.key = key;
    return country;
}

Usage

CountryDAO *cdao = [[CountryDAO alloc] init];
[cdao createCountry:1 key:@"goodtimebiz.us"];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

This example uses general context and MR_createEntity.
Very easy?
MR_saveToPersistentStoreAndWait is to commit.

Read

Find all

-(NSArray *)findAll {
    return [Country MR_findAll];
}

Find by attr

-(Country *)findByCode:(int)code {
    return [Country MR_findFirstByAttribute:@"code" withValue:[NSNumber numberWithInt:code]];
}

This is attribute search.

Truncate

To delete one item or several items, we use MR_deleteAllMatchingPredicate
To delete all(a lot of items), use trancate like MySQL.

-(void)deleteAll {
    [Country MR_truncateAll];
}

NSPredicate

To make a bit difficult SQL, we use NSPredicate in CoreData.
It is same as Magical Record.

.xcdatamodeld

Item

  • from Date
  • name String
  • to Date
  • uid String

Delete

-(void)deleteByUid:(NSString *)uid {
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uid == %@", uid];
    [Item MR_deleteAllMatchingPredicate:predicate];
}

To add condition, we use NSPredicate.

Predicate(condition)


-(NSArray *)findBetweenFromTo:(NSDate *)from to:(NSDate *)to {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@”(from >= %@) AND (to <= %@)”, from, to]; return [Item MR_findAllSortedBy:@”from” ascending:YES withPredicate:predicate]; } [/cpp]