【问题标题】:Xcode 4.6 ARC Warning for Game Center Authentication游戏中心身份验证的 Xcode 4.6 ARC 警告
【发布时间】:2013-01-30 22:31:19
【问题描述】:

这是一个编译器警告,仅在我将 XCode 更新到 4.6 时才出现。我的代码直接取自 Apple 的文档(顺便说一句,这是我的 iOS 6 代码)。

GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

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

警告--在此块中强捕获“localPlayer”可能会导致保留周期

【问题讨论】:

    标签: ios xcode automatic-ref-counting game-center xcode4.6


    【解决方案1】:

    问题是 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) {
            ...
    

    鉴于 authenticateHandler 和 localPlayer 的生命周期紧密相关(即当 localPlayer 被释放时,authenticHandler 也是如此),因此无需在 authenticateHandler 中维护强引用。使用 Xcode 4.6,这不再生成您提到的警告。

    【讨论】:

    • 谢谢!我现在对块保留周期有了更多的了解。这是完美的。
    • 你也可以不创建localPlayer变量而总是使用[GKLocalPlayer localPlayer],所以你不要保留任何引用。
    【解决方案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){
    

    【讨论】:

    • 这似乎对我不起作用。我可以弱创建localPlayer吗?我正在我的 AppDelegate 中进行此身份验证,因此没有相应的 viewController。
    • 是的,我读错了你的问题,并认为它在抱怨捕获自我。使用 Chris McGrath 发布的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2019-10-06
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多