Variable of AppDelegate used as global variable do

2019-05-21 04:16发布

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!

4条回答
萌系小妹纸
2楼-- · 2019-05-21 04:46

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/

查看更多
一纸荒年 Trace。
3楼-- · 2019-05-21 04:49

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

查看更多
姐就是有狂的资本
4楼-- · 2019-05-21 05:01

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

查看更多
Animai°情兽
5楼-- · 2019-05-21 05:03
@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.

查看更多
登录 后发表回答