【问题标题】:UIColor variable values are null for the first instance in iOSiOS 中的第一个实例的 UIColor 变量值为 null
【发布时间】:2026-01-07 13:45:01
【问题描述】:

我正在尝试在我的 AppDelegate.h 文件中创建一个 UIColor 变量和共享实例方法,它可用于在应用程序的任何位置访问此变量的值。下面是我的 AppDelegate.h 代码-

+(AppDelegate *)sharedInstance;
@property(nonatomic,strong) UIColor * darkColorC1;

对于 AppDelegate.m-

+ (AppDelegate *)sharedInstance {
static dispatch_once_t onceToken;
static AppDelegate *instance = nil;
dispatch_once(&onceToken, ^{
    instance = [[AppDelegate alloc] init];
});
return instance;
}

我有一个类在 tableview 上显示不同的颜色,当我尝试选择任何一种颜色时,它会保存到 NSUserDefaults 中。我正在尝试使用以下语句将 userdefaults 中保存的颜色分配给这个 darkcolorc1 变量-

AppDelegate *globals = [AppDelegate sharedInstance];
globals.darkColorC1 = color1;

我能够将 color1(Userdefaults) 值存储到我的 AppDelegate 变量 darkColorC1 中,当我关闭应用程序并尝试再次运行它时,我会在 Appdelegate 方法 -didFinishLaunchingWithOptions 中获得当前颜色选择值。但是当我尝试将该颜色分配给我的第一个视图控制器时,它显示空值。 例如-

AppDelegate *globals = [AppDelegate sharedInstance];
self.view.backgroundcolor= globals.darkColorC1;

它显示 globals.darkColorC1 的空值。

此外,当我尝试选择任何其他颜色并将其存储在 globals.darkColorC1 变量中并尝试加载我的第一个视图控制器时,这次值不为空。 谁能帮我解决这个问题。 任何帮助表示赞赏。

【问题讨论】:

  • AppDelegate 是自定义类,还是[[UIApplication sharedApplication] delegate]?
  • 它是 [[UIApplication sharedApplication] 委托]
  • 那你为什么有一个自定义的初始化和自定义的共享实例呢?
  • 那么我如何访问应用程序委托变量。你能告诉我怎么做吗?
  • AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; self.view.backgroundColor = appDelegate.darkColorC1;. But I wouldn't surcharge the UIApplicationDelegate` 用那种东西,然后创建另一个单例来做到这一点。

标签: ios objective-c appdelegate uicolor


【解决方案1】:

AppDelegate的对象不需要这样创建,可以这样使用AppDelegate的对象

AppDelegate *appDelObj = (AppDelegate *)[[UIApplication sharedApplication] delegate];

另外,你为什么要在AppDelegate 类中转储这种类型的变量,为你想在整个应用程序中访问的那些类型的变量创建一个单例。

举例

在 .h 类中

#import <Foundation/Foundation.h>

@interface MyDataHandler : NSObject

+ (instancetype)sharedDataHandler;

@property(nonatomic,strong) UIColor * darkColorC1;

@end

现在在你的 .m 类中

#import "MyDataHandler.h"

@implementation MyDataHandler

+ (MyDataHandler *) sharedDataHandler {
    static id _sharedHandler = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedHandler = [[self alloc] init];
    });
    return _sharedHandler;
}
- (id)init {
    if (self = [super init]) {
    }
    return self;
}
@end

现在你可以像这样访问这个变量了

[MyDataHandler sharedDataHandler].darkColorC1

【讨论】:

  • 好的。现在我明白了。感谢您的建议。但是你能告诉我这个类什么时候被调用或者我如何调用这个类的方法吗?
  • 我已经在答案中提到了 - [MyDataHandler sharedDataHandler].darkColorC1
最近更新 更多