Split NSData objects into other NSData objects of a given size

后端 未结 1 647
轻奢々
轻奢々 2020-12-01 03:55

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 t

相关标签:
1条回答
  • 2020-12-01 04:25

    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). chunk fragments point into memory owned by myBlob, so don't retain them unless you retain myBlob.

    0 讨论(0)
提交回复
热议问题