8

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sam
  • 2,707
  • 1
  • 23
  • 32

1 Answers1

3

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];
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yoshyosh
  • 13,956
  • 14
  • 38
  • 46