如何将 NSArray 转换为 NSData? [英] How to convert NSArray to NSData?

查看:63
本文介绍了如何将 NSArray 转换为 NSData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何将 NSArray 转换为 NSData?我有一个 NSArray.我需要将它发送到 NSInputStream.为此,我需要将 NSArray 转换为 NSData.

Can anyone tell me how to convert an NSArray to an NSData? I have an NSArray. I need to send it to an NSInputStream. In order to do that I need to convert the NSArray to an NSData.

请帮帮我,我被困在这里了.

Please help me, I'm stuck here.

推荐答案

使用 NSKeyedArchiver(这是 Garrett 帖子链接的最后一句):

Use NSKeyedArchiver (which is the last sentence of the post Garrett links):

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];

注意array中的所有对象都必须符合NSCoding协议.如果这些是自定义对象,那么这意味着您需要阅读 编码和解码对象.

Note that all the objects in array must conform to the NSCoding protocol. If these are custom objects, then that means you need to read up on Encoding and Decoding Objects.

请注意,这将创建一个相当难以阅读的属性列表格式,但可以处理非常广泛的对象.如果您有一个非常简单的数组(例如字符串),您可能需要使用 NSPropertyListSerialization,它会创建一个更简单的属性列表:

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:

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

如果您希望它在网络上可读,还可以传递一个 XML 格式常量.

There's also an XML format constant you can pass if you'd rather it be readable on the wire.

这篇关于如何将 NSArray 转换为 NSData?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆