Jos*_*ley -1 byte integer objective-c nsnumber nsdata
我正在使用Objective-C,我需要将NSArray中的int添加到NSMutableData(我正在准备通过连接发送数据).如果我用NSNumber包装int,然后将它们添加到NSMutableData,我怎么能找出NSNumber int中有多少字节?是否有可能使用sizeof(),因为根据Apple文档,"NSNumber是NSValue的子类,它提供任何C标量(数字)类型的值."?
例:
NSNumber *numero = [[NSNumber alloc] initWithInt:5];
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:numero length:sizeof(numero)];
Run Code Online (Sandbox Code Playgroud)
numero不是数值,它是指向代表数值的对象的指针.您要做的事情将无法工作,大小将始终等于指针(32位平台为4,64位为8),并且您将向数据添加一些垃圾指针值而不是数字.
即使您尝试取消引用它,也无法直接访问支持NSNumber的字节并期望它能够正常工作.发生了什么是内部实现细节,可能因版本而异,甚至可能在同一版本的不同配置之间(32位vs 64位,iPhone vs Mac OS X,arm vs i386 vs PPC).只是打包字节并通过线路发送它们可能会导致在另一端没有正确反序列化的东西,即使你设法获得实际数据.
你真的需要提出一个可以放入数据的整数编码,然后打包并解压缩NSNumbers.就像是:
NSNumber *myNumber = ... //(get a value somehow)
int32_t myInteger = [myNumber integerValue]; //Get the integerValue out of the number
int32_t networkInteger = htonl(myInteger); //Convert the integer to network endian
[data appendBytes:&networkInteger sizeof(networkInteger)]; //stuff it into the data
Run Code Online (Sandbox Code Playgroud)
然后在接收端获取整数并使用numberWithInteger重新创建一个NSNumber:在使用ntohl将其转换为本机主机格式之后.
如果您尝试发送最少的表示等,可能需要更多的工作.
另一种选择是使用NSCoder子类并告诉NSNumber使用你的编码器对自己进行编码,因为这将是平台中立的,但是对于你想要做的事情可能有点过分.