animal_chin
animal_chin

Reputation: 6610

Variable of AppDelegate used as global variable doesn't work

I would like to use my AppDelegate to store a object which will be accessible to any other classes. I've declared this AppDelegate like this :

@interface MyAppDelegate : UIResponder <UIApplicationDelegate>
{
    MyClass *tracker;
}

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ICViewController *viewController;
@property (retain, nonatomic) MyClass *tracker;

@end

I synthesize tracker and in application:didFinishLaunchingWithOptions: i set one NSString in that object like this :

self.tracker = [[MyClass alloc] init];
self.tracker.testGlobal = @"global funguje";

When i need to access tracker somewhere else in some other class i use this code :

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];    
MyClass *trackerTEST = appDelegate.tracker;
NSLog(@"TEST : %@",trackerTEST.testGlobal);

The problem is that testGlobal is NULL. What am I doing wrong? Also here are class files for MyClass :

@interface MyClass : NSObject
{
    NSString *testGlobal;
}
@property (retain, nonatomic) NSString *testGlobal;
@end

@implementation MyClass
@synthesize testGlobal = _testGlobal;
@end

Thanks for any kind of help!

Upvotes: 2

Views: 5524

Answers (4)

PrimaryChicken
PrimaryChicken

Reputation: 973

Change @synthesize testGlobal = _testGlobal; to @synthesize testGlobal; and try again.

Upvotes: 0

CarlJ
CarlJ

Reputation: 9481

maybe I'm answer to late but, you can take a look at the Singleton Pattern.

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.

Here is an ObjC implementation: http://getsetgames.com/2009/08/30/the-objective-c-singleton/

Upvotes: 4

DocJones
DocJones

Reputation: 677

Check if application:didFinishLaunchingWithOptions: is being called by adding a NSLog(@"..."). If trackerTEST is nil, it was possibly not correctly initialized.

Upvotes: 2

Jakub
Jakub

Reputation: 13860

@interface MyAppDelegate : UIResponder <UIApplicationDelegate>
{
    MyClass *tracker;
}

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ICViewController *viewController;
@property (retain, nonatomic) MyClass *tracker;

@end

Why you have @property tracker and var tracker?

Try to remove MyClass *tracker; property only should be enough.

Upvotes: 0

Related Questions