-->

的Xcode 4.6 ARC警告游戏中心认证(Xcode 4.6 ARC Warning for G

2019-08-16 15:48发布

这是一个新的编译器警告,只有出现了,当我Xcode更新到4.6。 我的代码是直接从苹果公司的文件解除(这是我的iOS 6的代码BTW)。

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
    [self setLastError:error];
    if(localPlayer.authenticated){

警告-捕获“localPlayer”强烈该块很可能会导致保留周期

Answer 1:

的问题是,localPlayer对象被保持的强引用本身 - 当localPlayer被“俘获”在authenticateHandler块内使用时,它被保持(当目标c对象块内参照,根据ARC的呼叫编译器保留为了你)。 现在,即使在localPlayer所有其他引用不复存在,它仍然具有1的保留计数,因此内存将永远不会被释放。 这就是为什么编译器给你一个警告。

是指它与弱引用,如:

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

__weak GKLocalPlayer *blockLocalPlayer = localPlayer;
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
    [self setLastError:error];
    if (blockLocalPlayer.authenticated) {
        ...

鉴于authenticateHandler和localPlayer的寿命是紧密相连(即当localPlayer被释放,所以是authenticateHandler)有没有必要为它保持authenticateHandler内很强的借鉴意义。 使用的Xcode 4.6,这不再产生你提到的警告。



Answer 2:

编译器只是帮助你解决代码已经是一个问题,它只是以前不知道这件事情。

:您可以了解这里保留周期http://www.cocoawithlove.com/2009/07/rules-to-avoid-retain-cycles.html

基本上你只需要更改您的代码是这样的:

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

__weak MyViewController *blockSelf = self;
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
    [blockSelf setLastError:error];
    if(localPlayer.authenticated){


文章来源: Xcode 4.6 ARC Warning for Game Center Authentication