mev*_*dev 10 xcode ios game-center automatic-ref-counting xcode4.6
这是一个新的编译器警告,只有在我将XCode更新为4.6时才出现.我的代码直接取自Apple的文档(这是我的iOS 6代码顺便说一句).
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
[self setLastError:error];
if(localPlayer.authenticated){
Run Code Online (Sandbox Code Playgroud)
警告 - 在此块中强烈捕获"localPlayer"可能会导致保留周期
Chr*_*ath 25
问题是localPlayer对象保持对自身的强引用 - 当localPlayer被"捕获"以在authenticateHandler块中使用时,它被保留(当在块中引用objective-c对象时,ARC调用下的编译器保留为了你).现在,即使对localPlayer的所有其他引用都不再存在,它仍将保留计数为1,因此永远不会释放内存.这就是编译器给你一个警告的原因.
请参考弱引用,例如:
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
__weak GKLocalPlayer *blockLocalPlayer = localPlayer;
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
[self setLastError:error];
if (blockLocalPlayer.authenticated) {
...
Run Code Online (Sandbox Code Playgroud)
鉴于authenticateHandler和localPlayer的生命周期紧密相关(即当localPlayer被解除分配时,authenticateHandler也是如此),因此不需要在authenticateHandler中维护强引用.使用Xcode 4.6,这不再生成您提到的警告.