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

查看:20
本文介绍了将 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天全站免登陆