与[[UIApplication sharedApplication]委托]有什么关系?

Chr*_*ris 4 iphone variables delegates

我正在使用[[UIApplication sharedApplication]委托]来跨多个类共享变量.我在AppDelegate中设置了值.我能够从myAppDelegate.m NSLog它并看到值.然后我尝试在我的一个Tabs加载时NSLog值,它崩溃了:

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

基本上似乎是在创建app.delegateVar的新实例?

delegateVar在myAppDelegate.h中定义,然后myAppDelegate.m我这样做:

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

        ...

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

    ...
    }
Run Code Online (Sandbox Code Playgroud)

Dav*_*har 6

一种可能性是delegateVar过早释放.

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

无论如何,请查看创建,分配和释放delegateVar的代码.


更新:

答对了.这是你的问题:

    [delegateVar release];
    delegateVar = [NSString stringWithFormat:@"Test Value"];
    NSLog(@"%@",delegateVar);
Run Code Online (Sandbox Code Playgroud)

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

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

self.delegateVar = [NSString stringWithFormat:@"Test Value"];
Run Code Online (Sandbox Code Playgroud)

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

  • 啊,是的,ol''过早释放'的问题. (2认同)