Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use RestKit and Realm.io?

Tags:

realm

restkit

I want to use RestKit, but I already use Realm.io instead of CoreData.

Is it possible to use RestKit on top of Realm.io?

like image 627
Sam Avatar asked Oct 08 '14 08:10

Sam


1 Answers

Sure you can. Once you get the object back from RestKit:

// GET a single Article from /articles/1234.json and map it into an object
// JSON looks like {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];
[mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/articles/:articleID" keyPath:@"article" statusCodes:statusCodes];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://restkit.org/articles/1234.json"]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
    Article *article = [result firstObject];


    // I would put the Realm write here


    NSLog(@"Mapped the article: %@", article);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Failed with error: %@", [error localizedDescription]);
}];
[operation start];

You will need to do two things:

  1. Create your RealmArticle model (in this case) that inherits from RLMObject
  2. Then you will just need to write to your realm

    RLMRealm *realm = [RLMRealm defaultRealm];
    
    [realm beginWriteTransaction];
    
    [RealmArticle createInDefaultRealmWithObject:article];
    
    [realm commitWriteTransaction];
    
like image 112
yoshyosh Avatar answered Nov 04 '22 00:11

yoshyosh