如何恢复操作 -[NSMutableData appendBytes:length:]?

How to revert action -[NSMutableData appendBytes:length:]?

From this link:

- (void)process {
    _isProcessing = YES;
    int amountInBuffer = 0;
    int framesRead = 0;

    do {
        if (_data.length >= BUFFER_SIZE) {
            framesRead = 1;
            break;
        }

        if (_shouldSeek) {
            [_decoder seek:seekFrame];
            _shouldSeek = NO;
        }
        int framesToRead = CHUNK_SIZE/bytesPerFrame;
        framesRead = [_decoder readAudio:inputBuffer frames:framesToRead];
        amountInBuffer = (framesRead * bytesPerFrame);

        dispatch_sync([ORGMQueues lock_queue], ^{
            [_data appendBytes:inputBuffer length:amountInBuffer];
        });
    } while (framesRead > 0);

    if (framesRead <= 0) {
        [self setEndOfInput:YES];
    }

    _isProcessing = NO;
}

我假设 bytesPerFrame 具有常数值。

所以void *inputBuffer用于通过块获取一些数据并将它们"compile"到NSMutableData对象中。如何还原此操作以将此对象转换回 void * 数据块数组(如果需要,包括内存管理)?

还有一些类似的问题但是:

1)他们只是将NSMutableData转换成void *,而不是void *数组;

2)他们没有考虑内存管理。

如果您需要复制所有内容,并且缓冲区被细分为相等的块,您可以这样做:

size_t nChunks = ... // How many frames
size_t frameSize = ... // Bytes per frame
void **data = malloc(sizeof(void*)*nChunks);
const char *raw = (const char*)_data.bytes;
for (size_t i = 0 ; i != nChunks ; i++) {
    data[i] = malloc(frameSize);
    memcpy(data[i], raw + i*frameSize, frameSize);
}

这时候你可以放开你的_data对象,因为所有的东西都被复制到void **data中了。当你不再需要这个数组时,你需要释放它:

for (size_t i = 0 ; i != nChunks ; i++) {
    free(data[i]);
}
free(data);