简体   繁体   English

如何将NSArray转换为NSData?

[英]How to convert NSArray to NSData?

Can anyone tell me how to convert an NSArray to an NSData ? 谁能告诉我如何将NSArray转换为NSData I have an NSArray . 我有一个NSArray I need to send it to an NSInputStream . 我需要将它发送到NSInputStream In order to do that I need to convert the NSArray to an NSData . 为此,我需要将NSArray转换为NSData

Please help me, I'm stuck here. 请帮助我,我被困在这里。

Use NSKeyedArchiver (which is the last sentence of the post Garrett links): 使用NSKeyedArchiver(这是Garrett帖子的最后一句话):

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];

Note that all the objects in array must conform to the NSCoding protocol. 请注意, array中的所有对象必须符合NSCoding协议。 If these are custom objects, then that means you need to read up on Encoding and Decoding Objects . 如果这些是自定义对象,那么这意味着您需要阅读编码和解码对象

Note that this will create a fairly hard-to-read property list format, but can handle a very wide range of objects. 请注意,这将创建一个相当难以阅读的属性列表格式,但可以处理各种各样的对象。 If you have a very simple array (strings for instance), you may want to use NSPropertyListSerialization, which creates a bit simpler property list: 如果你有一个非常简单的数组(例如字符串),你可能想要使用NSPropertyListSerialization,这会创建一个更简单的属性列表:

NSString *error;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:array format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error];

There's also an XML format constant you can pass if you'd rather it be readable on the wire. 如果您希望它在线上可读,那么您还可以传递XML格式常量。

在某种程度上相关的说明,这里是如何将NSData转换回NSArray:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]

我不确定这是否会对您有所帮助,但它是NSMutableArray与NSData的链接。

I used this code. 我用过这段代码。

 NSError *error;
 NSMutableData *jsonData = [[NSJSONSerialization dataWithJSONObject:yourDemoArray
                                                                   options:0 // Pass 0 if you don't care about the readability of the generated string
                                                                     error:&error] copy];

You can do this- 你可以这样做-

NSArray *array= [NSArray array];
NSData *dataArray = [NSKeyedArchiver archivedDataWithRootObject:array];

In iOS 9+ use this please: 在iOS 9+中使用此请:

NSArray *array = [[NSArray alloc] init];
NSData *data = [NSPropertyListSerialization dataWithPropertyList:array format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];

The older version of this was deprecated in iOS 8. 在iOS 8中不推荐使用旧版本。

Swift : 斯威夫特:

let data = NSKeyedArchiver.archivedData(withRootObject: jsonArray)
print(data)

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

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