【问题标题】:RestKit - mixing entity mapping and object mappingRestKit - 混合实体映射和对象映射
【发布时间】:2017-10-13 07:44:10
【问题描述】:
我在我的 iOS 应用程序中使用 RestKit,直到现在我只是使用对象映射,因为我没有将任何数据持久化到 CoreData。我现在想增加用户下载一些数据的可能性,并在用户没有互联网连接时使用这些数据。
我知道我必须为此使用实体映射,但我遇到了一个问题:如何为同一个请求使用两个不同的映射?我的意思是,我不明白我应该如何处理这两种情况。无论用户决定下载数据还是仅请求显示一次,URL 路径都将完全相同。如何告诉 RestKit 一次将其存储在 CoreData 中,而另一次则简单地使用 ObjectMapping 进行映射?
基本上,我问的问题和这个问题一样:How to use Core Data models without saving them?
但专门针对 RestKit 而不是 MagicalRecords。
【问题讨论】:
标签:
ios
core-data
restkit
【解决方案1】:
我刚刚遇到了类似的问题:除了要映射到 Core Data 的用户对象之外,我还需要获取一个正在返回的令牌。令牌是在 JSON 响应中自己发送的,所以我不确定如何提取它。
最后我使用了以下内容:
[operation setWillMapDeserializedResponseBlock:^id(id deserializedResponseBody) {
NSDictionary *dictionary = [[NSMutableDictionary alloc] init];
dictionary = deserializedResponseBody;
self.token = [dictionary objectForKey:@"token"];
return deserializedResponseBody;
}];
JSON 格式为:
{
“token”: “....”,
“user”: {
....
}
}
操作 setWillMapDeserializedResponseBlock 方法让您有机会在映射发生之前操纵结果 - 或获取对象映射未涵盖的其他数据。效果很好。
【解决方案2】:
处理这种情况的正确方法是使用不同的ManagedObjectContexts。
您将需要一个用于持久数据,可以这样设置:
// Initialize managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];
objectManager.managedObjectStore = managedObjectStore;
[managedObjectStore createPersistentStoreCoordinator];
[[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
然后,您可以创建第二个上下文,它只是临时的:
NSManagedObjectContext *newTemporaryContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; // Choose your concurrency type, or leave it off entirely
[newTemporaryContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
newTemporaryContext.persistentStoreCoordinator = coordinator;
最后,一旦完成,您应该在某处存储对临时上下文的引用,并根据应用的上下文决定使用哪个上下文。