遍历NSData并获取大块 [英] Iterate through NSData and grab chunks

查看:326
本文介绍了遍历NSData并获取大块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以遍历NSData,所以我可以根据特定的字节模式对其进行拆分?我需要将某些块分成数组以供以后查找.

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.

推荐答案

要在某些分隔符上分割NSData,可以使用rangeOfData:options:range:搜索分隔符,然后使用subdataWithRange:进行分割.例如(基于我目前正在使用的某些代码,但是我尚未测试此特定块):

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)];
  ...
}

此示例搜索delimiter,然后为bodyData分配所有字节.您可以编写类似的代码来分解内容并将其添加到数组中,或者随便添加.

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.

此方案比起自己的滚动方案的一个优势是,您将受益于NSData内部避免内存复制的任何优化.苹果公司不承诺进行此类优化,但是您可以看到它们在dispatch_dataenumerateByteRangesUsingBlock:的推动下正在向前发展.实际上,您应该尽可能避免使用bytes(*),因为这会强制NSData创建一个连续范围,直到这一点它都可以避免.

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.

有关更多信息,请参见二进制数据编程指南 . (请注意,本指南尚未针对iOS 7更新,并且没有讨论enumerateByteRangesUsingBlock:.)

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

(*)只要有可能"在这里有点强大,因为如果内存副本没问题的话,不要为了避免调用bytes而使代码不必要地复杂化.

(*) "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.

这篇关于遍历NSData并获取大块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆