将NSData对象拆分为给定大小的其他NSData对象 [英] Split NSData objects into other NSData objects of a given size

查看:318
本文介绍了将NSData对象拆分为给定大小的其他NSData对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约1000kB的NSData对象。现在我想通过蓝牙传输这个。如果我拥有10个100kB的物体,那会更好。我想到我应该使用NSData的 -subdataWithRange:方法。

I have an NSData object of approximately 1000kB in size. Now I want to transfer this via Bluetooth. It would be better if I have, let's say, 10 objects of 100kB. It comes to mind that I should use the -subdataWithRange: method of NSData.

我还没有真正工作过与NSRange。好吧,我知道它是如何工作的,但我无法弄清楚如何从一个给定位置读取长度:'到文件结尾'......我不知道该怎么做。

I haven't really worked with NSRange. Well, I know how it works, but I can't figure out how to read from a given location with the length: 'to end of file'... I've no idea how to do that.

有关如何将其拆分为多个100kB NSData对象的一些代码将真正帮助我。 (它可能涉及 -length 方法来查看应该制作多少个对象..?)

Some code on how to split this into multiple 100kB NSData objects would really help me out here. (it probably involves the -length method to see how many objects should be made..?)

谢谢提前。

推荐答案

以下代码片段在没有复制数据的情况下进行碎片:

The following piece of code does the fragmentation without copying the data:

NSData* myBlob;
NSUInteger length = [myBlob length];
NSUInteger chunkSize = 100 * 1024;
NSUInteger offset = 0;
do {
    NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
    NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[myBlob bytes] + offset
                                         length:thisChunkSize
                                   freeWhenDone:NO];
    offset += thisChunkSize;
    // do something with chunk
} while (offset < length);

旁注:我应该补充一点,在 myBlob之后无法安全地使用块对象已经发布(或以其他方式修改)。 chunk 片段指向 myBlob 所拥有的内存,因此除非保留,否则不要保留它们myBlob

Sidenote: I should add that the chunk objects cannot safely be used after myBlob has been released (or otherwise modified). chunk fragments point into memory owned by myBlob, so don't retain them unless you retain myBlob.

这篇关于将NSData对象拆分为给定大小的其他NSData对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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