简体   繁体   中英

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:

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.

You could also use getBytes:len: as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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