Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the deal with [[UIApplication sharedApplication] delegate]?

I am using [[UIApplication sharedApplication] delegate] to share a variable across several classes. I set the value in the AppDelegate. I am able to NSLog it from the myAppDelegate.m and see the value. Then I try to NSLog the value when one of my Tabs loads, and it crashes:

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

Basically seems like it is creating a new instance of app.delegateVar ?

delegateVar is defined in myAppDelegate.h and then it myAppDelegate.m I do this:

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

        ...

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

    ...
    }
like image 653
Chris Avatar asked Feb 25 '23 20:02

Chris


1 Answers

One possibility is that delegateVar is being released prematurely.

For example, maybe the delegateVar property is not set up with the retain option, you are explicitly calling [delegateVar release], or you are bypassing the setter (and its retain semantics) by assigning directly to it (delegateVar = instead of self.delegateVar =).

In any case, look at the code that creates, assigns, and releases delegateVar.


Update:

Bingo. This is your problem right here:

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

You are assigning an autoreleased value (from +NSString stringWithFormat:) to delegateVar, and are not doing anything to retain it. That means that as soon as applicationDidFinishLaunching: returns, delegateVar is automatically released (and becomes invalid).

If delegateVar is a property with the "retain" option defined, you should be doing this as:

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

You don't need to release delegateVar before assigning to it (using self.delegateVar =), because the setter will release the old value as needed. But you do need to release it in your dealloc method.

like image 102
David Gelhar Avatar answered Apr 14 '23 14:04

David Gelhar