NSCoding 和整数数组
如何使用 NSCoding 来编码(和解码)一个由 10 个基本类型 int
值组成的数组?单独编码每个整数(在 for 循环中)。但是如果我的数组包含一百万个整数怎么办?除了使用 for 循环之外,还有更令人满意的替代方法吗?
编辑(第一个答案后):解码? (@Justin:然后我会勾选你的答案。)
How do you use NSCoding to code (and decode) an array of of ten values of primitive type int
? Encode each integer individually (in a for-loop). But what if my array held one million integers? Is there a more satisfying alternative to using a for-loop here?
Edit (after first answer): And decode? (@Justin: I'll then tick your answer.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您关心性能:CFData/NSData 符合 NSCoding 标准,因此只需将数组的序列化表示包装为 NSCFData 即可。
编辑详细编码/解码:
您的整数数组需要转换为通用字节序格式(取决于机器的字节序) - 例如始终将其存储为小字节序或大字节序。在编码过程中,将其转换为指定字节顺序的整数数组,并将其传递给 NSData 对象。然后将 NSData 表示传递给 NSCoder 实例。在解码时,您将收到密钥的 NSData 对象,在解码时有条件地将其转换为机器的本机字节序。一组可用于 OS X 和 iOS 的字节交换例程以
OSSwap*
开头。或者,请参阅
-[NSCoderencodeBytes:voidPtr length:numBytes forKey:key]
。此例程还要求客户端交换字节顺序。If performance is your concern here: CFData/NSData is NSCoding compliant, so just wrap your serialized representation of the array as NSCFData.
edit to detail encoding/decoding:
your array of ints will need to to be converted to a common endian format (depending on the machine's endianness) - e.g. always store it as little or big endian. during encoding, convert it to an array of integers in the specified endianness, which is passed to the NSData object. then pass the NSData representation to the NSCoder instance. at decode, you'll receive an NSData object for the key, you conditionally convert it to the native endianness of the machine when decoding it. one set of byte swapping routines available for OS X and iOS begin with
OSSwap*
.alternatively, see
-[NSCoder encodeBytes:voidPtr length:numBytes forKey:key]
. this routine also requires the client to swap endianness.