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

时间:2015-09-25 13:44:42

标签: ios objective-c core-audio void-pointers nsmutabledata

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用于通过块获取一些数据并且#34;编译&#34;他们进入NSMutableData对象。如何恢复此操作以将此对象转换回void *数据块的数组(如果需要,还包括内存管理)?

有一些类似的问题但是:

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

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

1 个答案:

答案 0 :(得分:0)

如果你需要复制一切,并且缓冲区被细分为相同的块,你可以这样做:

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