gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:19:49 24 4
gpt4 key购买 nike

我想使用我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com