Objective c 用作全局变量的AppDelegate的变量不';行不通

Objective c 用作全局变量的AppDelegate的变量不';行不通,objective-c,ios,xcode,class,Objective C,Ios,Xcode,Class,我想使用我的AppDelegate来存储一个对象,该对象可以被任何其他类访问。我已经这样声明了这个AppDelegate: @interface MyAppDelegate : UIResponder <UIApplicationDelegate> { MyClass *tracker; } @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) ICViewControll

我想使用我的AppDelegate来存储一个对象,该对象可以被任何其他类访问。我已经这样声明了这个AppDelegate:

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

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

@end
self.tracker = [[MyClass alloc] init];
self.tracker.testGlobal = @"global funguje";
当我需要访问其他类中的其他地方时,我使用以下代码:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];    
MyClass *trackerTEST = appDelegate.tracker;
NSLog(@"TEST : %@",trackerTEST.testGlobal);
问题是testGlobal为NULL。我做错了什么?这里还有MyClass的类文件:

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

@implementation MyClass
@synthesize testGlobal = _testGlobal;
@end
谢谢你的帮助

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

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

@end
{ MyClass*跟踪器; } @属性(强,非原子)UIWindow*window; @属性(强,非原子)ICViewController*viewController; @属性(保留,非原子)MyClass*跟踪器; @结束
为什么有@property tracker和var tracker


尝试删除
MyClass*跟踪器属性就足够了。

更改
@synthetic testGlobal=\u testGlobal
@testGlobal
并重试。

检查是否通过添加
NSLog(@“…”)
调用了
应用程序:DidFinishLaunchWithOptions:
。如果
trackerTEST
为nil,则可能未正确初始化。

可能是我晚了,但是,您可以查看

在软件工程中,singleton模式是一种设计模式,用于通过将类的实例化限制为一个对象来实现singleton的数学概念。当需要一个对象来协调整个系统中的操作时,这非常有用。这一概念有时被推广到只有一个对象时运行效率更高的系统,或者将实例化限制在一定数量的对象上的系统


这是一个ObjC实现:

你说
testGlobal
为零,但是你确定
trackerTEST
appDelegate
也不是零吗?我们刚刚发现appDelegate很好,但是trackerTEST为零……嗯……我做错了什么?:)好吧,我绝望了,所以我试着在那里添加:)但删除它没有帮助,它仍然是零…:/也没有帮助…:/问题是我从appdelegate获得的对象为零…谢谢!多亏了你,我终于明白了…这真是一个愚蠢的错误:)我在应用程序末尾初始化了跟踪器:didfishlaunchingwithoptions:,这是在我使用。。。grrr:)谢谢,真的:)不客气。我建议将初始化重新定位到
init
方法。但我不太清楚这是不是一个像样的解决方案恐怕不晚。。。这是一个很好的答案;)但后来我决定使用这种方法…在这种情况下,单例对我来说太复杂了。。。不过还是谢谢你