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

查看:78
本文介绍了如何将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];

请注意数组中的所有对象必须符合 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天全站免登陆