简体   繁体   English

如何使用RestKit将Core Data对象数组序列化为字符串数组?

[英]How to serialize an array of Core Data objects into an array of string using RestKit?

I am currently using RestKit version 0.20.3 in my iOS project to communicate with my backend web service. 我当前在iOS项目中使用RestKit版本0.20.3与后端Web服务进行通信。

In some cases, my web service returns an array of tags (django-taggit) in string format and I needed to map each tag string into a core data entity. 在某些情况下,我的Web服务以字符串格式返回一个标签数组(django-taggit),我需要将每个标签字符串映射到一个核心数据实体中。

// example JSON from web service

"response" : { "tags": ["tag1", "tag2", "tag3"] }


// example Core Data entities

@interface TagEntity : NSManagedObject

@property (nonatomic, retain) NSString *tagName;

@end

From the below discussion, I found a way to map an array of tag strings into core data objects. 从下面的讨论中,我找到了一种将标记字符串数组映射到核心数据对象的方法。

https://groups.google.com/forum/#!topic/restkit/54eZFQIjl7c https://groups.google.com/forum/#!topic/restkit/54eZFQIjl7c

tagEntityMapping = [RKEntityMapping mappingForEntityForName:@"TagEntity" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
[tagEntityMapping addPropertyMapping:[RKAttributeMapping mappingFromKeyPath:nil toKeyPath:@"tagName"]]
tagEntityMapping.identificationAttributes = @[@"tagName"];
[resultEntityMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"tags" toKeyPath:@"tags"withMapping:tagEntityMapping]];

Now, I am looking for a way to post an array of tag strings from Core Data objects to web service. 现在,我正在寻找一种将标记字符串数组从Core Data对象发布到Web服务的方法。

In other words, given that I have an array of TagEntity Core Data objects, I wish to send an array of [TagEntity tagName] 换句话说,假设我有一个TagEntity Core Data对象数组,我希望发送一个[TagEntity tagName]数组

To achieve this, I used [resultEntityMapping inverseMapping] as a request mapping, but as result, I get 为此,我使用[resultEntityMapping inverseMapping]作为请求映射,但是结果是

"request" : { "tags": [{"tag1": {}}, {"tag2": {}}, {"tag3": {}}] }

while what I really wish to get is 而我真正希望得到的是

"request" : { "tags": ["tag1", "tag2", "tag3"] }

I would appreciate any help. 我将不胜感激任何帮助。 Thanks! 谢谢!

If you just have an array of TagEntity instances then you can get the array of strings with: 如果只有一个TagEntity实例数组,则可以使用以下命令获取字符串数组:

NSArray *tagStrings = [tags valueForKey:@"tagName"];

Once you have that you can pass the array to RestKit (wrapped into an NSDictionary based on your sample JSON) or use NSJSONSerialization directly and use the underlying AFNetworking provided API to send the JSON. 一旦有了它,就可以将数组传递给RestKit(根据示例JSON包装到NSDictionary ),或者直接使用NSJSONSerialization并使用基础AFNetworking提供的API发送JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM