objective-c - NSMutableData 删除字节?

标签 objective-c nsdata nsmutabledata

我可以使用 appendData 方法轻松地将字节添加到 NSMutableData 实例,但是我没有看到任何类似的删除数据的方法?我是否忽略了什么,或者我是否需要创建一个新对象并仅复制我需要的字节?

最佳答案

请查看以下方法的文档:

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)replacementBytes length:(NSUInteger)replacementLength

Apple 明确表示如下:

If the length of range is not equal to replacementLength, the receiver is resized to accommodate the new bytes. Any bytes past range in the receiver are shifted to accommodate the new bytes. You can therefore pass NULL for replacementBytes and 0 for replacementLength to delete bytes in the receiver in the range range. You can also replace a range (which might be zero-length) with more bytes than the length of the range, which has the effect of insertion (or “replace some and insert more”).

要从末尾删除 10 个字节,请使用:

[data setLength:[data length] - 10];

它也可以通过 replaceBytesInRange 来完成,但实际上它要快得多,因为字节并没有真正被删除。相反,只有内部大小变量被更改,NSMutableData 的行为就像删除了字节一样。 IOW,这是一个 O(1) 操作(这意味着无论您删除多少字节,它总是需要同样长的时间来执行),而且速度非常快。

要从前面删除 10 个字节,请使用:

[data replaceBytesInRange:NSMakeRange(0, 10) withBytes:NULL length:0];

要删除中间的 10 个字节(例如,在 20 个字节之后),请使用:

[data replaceBytesInRange:NSMakeRange(20, 10) withBytes:NULL length:0];

不过,replaceBytesInRange 是一个复杂度为 O(n) 的操作。这意味着无论删除 100 个字节需要多长时间,删除 200 个字节将花费两倍的时间,依此类推。它仍然非常快,并且仅受计算机内存 (RAM) 吞吐量的限制。如果您有 10 MB 的数据并从前面删除 1 MB,则会复制 9 MB 以填补刚删除的 MB 的空白。因此,操作的速度取决于您的系统将 9 MB RAM 从一个地址移动到另一个地址的速度。这通常足够快,除非您处理包含数百 MB 的 NSMutableData 对象。

关于objective-c - NSMutableData 删除字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2345626/

相关文章:

iphone - 我可以更改uitableview的tableHeaderView的高度吗?

iphone - NSData dataWithContentsOfURL 缓存

cocoa-touch - 如何避免 NSUrlConnection 的多个实例的数据损坏

ios - 如何使用字节数据创建 uint8_t?

ios - 使用从 Web 服务接收到的 nsmutable 数据填充 tableview

ios - 自定义 UITableViewCell 中 UIView 的仅两个角 - iOS

objective-c - 调用 NSDictionary 中所有包含 JSON 对象的 Key 时出错

ios - Facebook SDK 集成 - 返回

ios - 单独的 NSData 对象

ios - 如何将 NSData 对象转换为 UIImage?使用 swift