为什么 subdataWithRange 会导致任何 NSThread 中的内存泄漏?
Why subdataWithRange leads to Memory Leak in any NSThread?
我对此感到困惑。我认为 ARC 可以处理这里的内存。在此 if 语句之后永远不会使用 subData。
if ([_buffer length] >= _bufferSize) {
NSRange range = NSMakeRange(0, _bufferSize);
NSData *subData = [_buffer subdataWithRange:range];
// Call the delegate method to deal with the new data
[_delegate inputQueue:self inputData:subData numberOfPackets:inNumberPacketDescriptions];
// Remove the transmitted data
[_buffer replaceBytesInRange:range withBytes:NULL length:0];
}
但是调用 subdataWithRange
会导致内存泄漏。 subData
永远不会被释放。我发现有人说subdataWithRange在NSThread下肯定会导致内存泄漏。但是为什么?
缓冲区来自AudioQueue,当AudioQueue中的一个队列被填满时调用此函数。此代码应在 AudioQueue 的内部线程上 运行。
通过添加自动释放池,解决了泄漏问题。但是为什么...
if ([_buffer length] >= _bufferSize) {
@autoreleasepool {
NSRange range = NSMakeRange(0, _bufferSize);
NSData *subData = [_buffer subdataWithRange:range];
// Call the delegate method to deal with the new data
[_delegate inputQueue:self inputData:subData numberOfPackets:inNumberPacketDescriptions];
// Remove the transmitted data
[_buffer replaceBytesInRange:range withBytes:NULL length:0];
}
}
所有 NSThreads 都以这种方式泄漏。 NSThreads 没有自己的自动释放池。在除主线程之外的任何线程上执行时,您必须总是做的第一件事是创建一个自动释放池。当然最好从一开始就不要使用 NSThread。这就是为什么有 GCD。
我对此感到困惑。我认为 ARC 可以处理这里的内存。在此 if 语句之后永远不会使用 subData。
if ([_buffer length] >= _bufferSize) {
NSRange range = NSMakeRange(0, _bufferSize);
NSData *subData = [_buffer subdataWithRange:range];
// Call the delegate method to deal with the new data
[_delegate inputQueue:self inputData:subData numberOfPackets:inNumberPacketDescriptions];
// Remove the transmitted data
[_buffer replaceBytesInRange:range withBytes:NULL length:0];
}
但是调用 subdataWithRange
会导致内存泄漏。 subData
永远不会被释放。我发现有人说subdataWithRange在NSThread下肯定会导致内存泄漏。但是为什么?
缓冲区来自AudioQueue,当AudioQueue中的一个队列被填满时调用此函数。此代码应在 AudioQueue 的内部线程上 运行。
通过添加自动释放池,解决了泄漏问题。但是为什么...
if ([_buffer length] >= _bufferSize) {
@autoreleasepool {
NSRange range = NSMakeRange(0, _bufferSize);
NSData *subData = [_buffer subdataWithRange:range];
// Call the delegate method to deal with the new data
[_delegate inputQueue:self inputData:subData numberOfPackets:inNumberPacketDescriptions];
// Remove the transmitted data
[_buffer replaceBytesInRange:range withBytes:NULL length:0];
}
}
所有 NSThreads 都以这种方式泄漏。 NSThreads 没有自己的自动释放池。在除主线程之外的任何线程上执行时,您必须总是做的第一件事是创建一个自动释放池。当然最好从一开始就不要使用 NSThread。这就是为什么有 GCD。