简体   繁体   English

iPhone NSMutableData字节索引

[英]iphone NSMutableData bytes index

for example,I want to get the value of instance of NSMutableData by an index,how should I do?I do it like this: 例如,我想通过索引获取NSMutableData实例的值,该怎么办?我是这样做的:

Byte *tempByte = (Byte*)malloc(1); 
memcpy(tempByte, [[nsmutabledata subdataWithRange:NSMakeRange(5, 5)] bytes], 1) ;

but I think it is not a good method. 但我认为这不是一个好方法。 update: I have solved the problem.thank you... 更新:我已经解决了问题。谢谢...

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

This code will dynamically allocate the array to the correct size (you must free(byteData) when you're done) and copy the bytes into it. 这段代码将动态地将数组分配给正确的大小(完成后必须释放(byteData))并将字节复制到其中。

You could also use getBytes:len: as indicated by others if you want to use a fixed length array. 如果要使用固定长度的数组,也可以使用其他人指出的getBytes:len:。 This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it. 这样可以避免malloc / free,但是扩展性较差,更容易出现缓冲区溢出问题,因此我很少使用它。

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

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