Iterate through NSData and grab chunks

后端 未结 1 1549
攒了一身酷
攒了一身酷 2021-01-22 16:27

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条回答
  • 2021-01-22 17:24

    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.

    0 讨论(0)
提交回复
热议问题