Chris
Chris

Reputation: 5627

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);

    ...
    }

Upvotes: 4

Views: 3622

Answers (2)

dreamlax
dreamlax

Reputation: 95365

David Gelhar has likely found the cause of the issue, however when you have memory management issues (EXC_BAD_ACCESS is a sign of memory management problems), there are a number of things you can do:

  1. Re-read the Cocoa memory management rules and make sure that you're following them.
  2. Run the static analyser. This will often pick up places where you have neglected the memory management rules.
  3. Try using NSZombieEnabled to find out whether you are sending messages to unallocated instances.

Upvotes: 2

David Gelhar
David Gelhar

Reputation: 27900

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.

Upvotes: 6

Related Questions