简体   繁体   English

将NSData对象拆分为给定大小的其他NSData对象

[英]Split NSData objects into other NSData objects of a given size

I have an NSData object of approximately 1000kB in size. 我有一个大约1000kB的NSData对象。 Now I want to transfer this via Bluetooth. 现在我想通过蓝牙传输。 It would be better if I have, let's say, 10 objects of 100kB. 如果我拥有10个100kB的物体,那会更好。 It comes to mind that I should use the -subdataWithRange: method of NSData. 我想到我应该使用NSData的-subdataWithRange:方法。

I haven't really worked with NSRange. 我没有真正使用过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. 好吧,我知道它是如何工作的,但我无法弄清楚如何从一个给定位置读取长度:'到文件末尾'......我不知道该怎么做。

Some code on how to split this into multiple 100kB NSData objects would really help me out here. 有关如何将其拆分为多个100kB NSData对象的一些代码将真正帮助我。 (it probably involves the -length method to see how many objects should be made..?) (它可能涉及-length方法来查看应该制作多少个对象..?)

Thank you in advance. 先感谢您。

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);

Sidenote: I should add that the chunk objects cannot safely be used after myBlob has been released (or otherwise modified). 旁注:我应该补充说, myBlob发布(或以其他方式修改)之后,无法安全地使用块对象。 chunk fragments point into memory owned by myBlob , so don't retain them unless you retain myBlob . chunk片段指向myBlob拥有的myBlob ,因此除非保留myBlob否则不要保留它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM