在启用ARC的C代码中执行Objective-C代码时,运行时内存泄漏警告
ARC被启用, bufferReady
被一个C ++库(非ARC启用)触发,我确定我在某处丢失了一个ARC。 请指教。 提前致谢。
用下面的代码:
@implementation HelloWorldLayer id refToSelf; //reference to self int shakeCounter = 0; void bufferReady() { if (shakeCounter % 100 == 0) { [refToSelf shakes]; } shakeCounter++; } - (void) shakes { CCRotateBy * rotate = [CCRotateBy actionWithDuration:0.1 angle:2]; CCActionInterval * rotateReverse = [rotate reverse]; CCSequence * seq1 = [CCSequence actions:rotate, rotateReverse, nil]; CCMoveBy * shake = [CCMoveBy actionWithDuration:0.1 position:ccp(5, 0)]; CCActionInterval * shakeReverse = [shake reverse]; CCSequence * seq2 = [CCSequence actions:shake, shakeReverse, nil]; CCSpawn * spawner = [CCSpawn actions:seq1, seq2, nil]; CCSequence * lastSequence = [CCSequence actions:spawner, spawner, spawner, spawner, nil]; [self runAction:lastSequence]; } - (id) init { if((self = [super init])) { ... } refToSelf = self; return self; }
在运行期间,每次执行shakes
都会收到内存泄漏警告。
objc[10060]: Object 0x466830 of class CCRotateBy autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x44cb70 of class CCRotateBy autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x46b260 of class CCSequence autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x45a790 of class CCMoveBy autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x469150 of class CCMoveBy autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x469190 of class CCSequence autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x46b350 of class CCSpawn autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x46b380 of class CCSequence autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x46b3b0 of class CCSequence autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug objc[10060]: Object 0x46bc00 of class CCSequence autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
你不会错过“ARC演员”。
我想你的C ++创build一个单独的线程,并在该线程上调用bufferReady
。 由于它是一个C ++库,我认为它不知道Objective-C或Cocoa内存pipe理的任何内容,所以它不会创build一个autorelease池。 因此你应该在bufferReady
创build一个自动释放池:
void bufferReady() { if (shakeCounter % 100 == 0) { @autoreleasepool { [refToSelf shakes]; } } shakeCounter++; }
但是我也看到,在shakes
,您正在创buildCocos2D对象并将runAction:
发送给自己,据推测可以运行您创build的操作对象。 你确定在随机线程上做这件事是安全的吗? 也许你应该发送自己的主线。 这是一个简单的方法来做到这一点:
void bufferReady() { if (shakeCounter % 100 == 0) { dispatch_async(dispatch_get_main_queue(), ^{ [refToSelf shakes]; }); } shakeCounter++; }
由于主线程pipe理自己的自动释放池,所以在这种情况下不必设置一个。