Variable of AppDelegate used as global variable doesn't work

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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!

回答1:

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



回答2:

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/



回答3:

@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.



回答4:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!