Iterate through NSData and grab chunks

余生长醉 提交于 2019-12-02 03:47:53

问题


IS there any way to iterate through NSData so I can split it based on specific byte patterns? I need to break of certain chunks into an array for later look up.


回答1:


To split an NSData on some separator, you can search for the separator with rangeOfData:options:range: and then split using subdataWithRange:. For example (based on some code I'm currently working on, but I haven't tested this specific block):

NSRange range = [data rangeOfData:delimiter
                          options:0
                            range:NSMakeRange(0, data.length)];
if (range.location != NSNotFound) {
  size_t body_offset = NSMaxRange(range);
  size_t body_size = data.length - body_offset;
  NSData *bodyData = [data subdataWithRange:NSMakeRange(body_offset, body_size)];
  ...
}

This example searches for delimiter and assigns bodyData all the bytes after that. You could write similar code to split things up and add them to an array, or whatever you like.

One advantage of this scheme over rolling your own is that you will benefit from any optimizations inside of NSData that avoid memory copies. Apple doesn't promise such optimizations, but you can see that they're moving that way with dispatch_data and enumerateByteRangesUsingBlock:. In fact, you should avoid bytes whenever possible (*), since that forces NSData to create a contiguous range, which it may have avoided up to that point.

For more, see the Binary Data Programming Guide. (Note that this guide has not been updated for iOS 7, and doesn't discuss enumerateByteRangesUsingBlock:.)

(*) "Whenever possible" is a little strong here, since you shouldn't make your code unnecessarily complicated just to avoid a call to bytes if memory copies wouldn't be a problem.



来源:https://stackoverflow.com/questions/19251099/iterate-through-nsdata-and-grab-chunks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!