我可以使用 RestKit 和 Realm.io 吗?
Posted
技术标签:
【中文标题】我可以使用 RestKit 和 Realm.io 吗?【英文标题】:Can I use RestKit and Realm.io? 【发布时间】:2014-10-08 08:50:11 【问题描述】:我想使用RestKit,但我已经使用Realm.io 而不是CoreData。
是否可以在 Realm.io 之上使用 RestKit?
【问题讨论】:
【参考方案1】:当然可以。从 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];
你需要做两件事:
-
创建继承自 RLMObject 的 RealmArticle 模型(在本例中)
那么你只需要写信到你的领域
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[RealmArticle createInDefaultRealmWithObject:article];
[realm commitWriteTransaction];
【讨论】:
以上是关于我可以使用 RestKit 和 Realm.io 吗?的主要内容,如果未能解决你的问题,请参考以下文章
将文件路径保存到 realm.io 并使用 AlamofireImage 分配图像