Reputation: 5627
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
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:
NSZombieEnabled
to find out whether you are sending messages to unallocated instances.Upvotes: 2
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