objective-c - 用作全局变量的 AppDelegate 变量不起作用

标签 objective-c ios xcode class

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

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

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

@end

我在 application:didFinishLaunchingWithOptions 中合成跟踪器:我在该对象中设置一个 NSString,如下所示:

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

当我需要在其他类(class)的其他地方访问跟踪器时,我使用此代码:

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

感谢您的帮助!

最佳答案

也许我回答晚了,但你可以看看 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.

这是一个 ObjC 实现:http://getsetgames.com/2009/08/30/the-objective-c-singleton/

关于objective-c - 用作全局变量的 AppDelegate 变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10243635/

相关文章:

ios - Spritekit 中的新场景没有显示任何内容?

ios - 使用自动布局将 View 定位在主页按钮一侧

iphone - -[NSFileManager removeItemAtPath :error:] makes app CRASH

swift - 线程 1 : EXC_BREAKPOINT (code=1, 子代码 = 0x10136bb50) - swift

ios - obj_msgSend CPU 使用率 100%

ios - 从转换后的 UIImageView 裁剪 UIImage

iOS清空请求队列

iphone - 访问外部包中的图像

iphone - 将 RSS 提要导入 Core Data 时防止重复

objective-c - 如何正确处理 NSTextField 中的 <Return> + 修饰键?