【问题标题】:What's the deal with [[UIApplication sharedApplication] delegate]?[[UIApplication sharedApplication] delegate] 是怎么回事?
【发布时间】:2010-11-12 03:14:48
【问题描述】:

我正在使用 [[UIApplication sharedApplication] delegate] 在多个类之间共享一个变量。我在 AppDelegate 中设置了值。我可以从 myAppDelegate.m NSLog 它并查看值。然后,当我的一个选项卡加载时,我尝试 NSLog 值,它崩溃了:

myAppDelegate *app = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"Value:%@ ", app.delegateVar); // <--- Causes Crash

基本上好像它正在创建一个新的 app.delegateVar 实例?

delegateVar 在 myAppDelegate.h 中定义,然后在 myAppDelegate.m 中定义:

  - (void)applicationDidFinishLaunching:(UIApplication *)application {

        ...

        [delegateVar release];
        delegateVar = [NSString stringWithFormat:@"Test Value"];
        NSLog(@"%@",delegateVar);

    ...
    }

【问题讨论】:

  • delegateVar 属性是什么以及它是如何定义的?
  • 您的应用委托类的名称是什么?正常的命名约定是让AppDelegate.m 包含一个名为AppDelegate 的类,而不是myAppDelegate。 (并且类名按惯例大写,因此“myAppDelegate *app = ...”看起来很可疑。
  • 命名不一致只是我发帖时编辑的错误。
  • delegateVar 是一个 NSMutableArray。我在 myAppDelegate.m 中定义它...请参阅上面的编辑。
  • “导致崩溃”如何?你到底遇到了什么错误?

标签: iphone variables delegates


【解决方案1】:

一种可能是delegateVar 被提前释放。

例如,delegateVar 属性可能没有使用retain 选项设置,您显式调用[delegateVar release],或者您通过直接分配给它(delegateVar =)绕过了setter(及其保留语义)而不是self.delegateVar =)。

无论如何,看看创建、分配和释放delegateVar的代码。


更新:

宾果游戏。 这是你的问题:

    [delegateVar release];
    delegateVar = [NSString stringWithFormat:@"Test Value"];
    NSLog(@"%@",delegateVar);

您正在将一个自动释放的值(来自 +NSString stringWithFormat:) 分配给 delegateVar,并且没有做任何事情来保留它。这意味着只要applicationDidFinishLaunching: 返回,delegateVar 就会自动释放(并变为无效)。

如果 delegateVar 是一个定义了“retain”选项的属性,你应该这样做:

self.delegateVar = [NSString stringWithFormat:@"Test Value"];

你不需要在分配之前释放delegateVar(使用self.delegateVar =),因为setter会根据需要释放旧值。但是您确实需要在您的dealloc 方法中释放它。

【讨论】:

  • 啊,是的,老“过早发布”问题。
  • 过早发布是一个严重的问题。我有朋友患有过早释放,而只是提高对这种情况的认识可以帮助其他过早释放者面对他们的问题并找到解决问题的方法。
  • 是的,看起来这是一个过早发布的问题。并认为我的女朋友从不抱怨......
【解决方案2】:

David Gelhar 可能已经找到了问题的原因,但是当您遇到内存管理问题(EXC_BAD_ACCESS 是内存管理问题的标志)时,您可以做很多事情:

  1. 重新阅读 Cocoa memory management rules 并确保您关注它们。
  2. 运行static analyser。这通常会发现您忽略了内存管理规则的地方。
  3. 尝试使用NSZombieEnabled 确定您是否正在向未分配的实例发送消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多