You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改window背景色时didFinishLaunchingWithOptions方法崩溃如何解决?

崩溃原因分析
  • 核心报错unrecognized selector sent to instance指向setWindow:方法,说明你的AppDelegate类没有声明对应的window属性,无法识别window的setter方法,调用self.window时触发了未实现方法的崩溃。
  • 常见触发场景:iOS 13及以上版本新建项目默认采用SceneDelegate管理生命周期,Xcode默认不会在AppDelegate中自动生成window属性,如果你没有手动声明就直接调用self.window就会出现该报错。
解决方案

分两种场景处理:

场景1:不需要适配iOS 12及以下版本,使用SceneDelegate管理UI

把设置window背景色的逻辑移到SceneDelegate的scene:willConnectToSession:options:方法中,SceneDelegate默认自带window属性,代码示例:

- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    if (![scene isKindOfClass:[UIWindowScene class]]) {
        return;
    }
    UIWindowScene *windowScene = (UIWindowScene *)scene;
    self.window = [[UIWindow alloc] initWithWindowScene:windowScene];
    self.window.backgroundColor = [UIColor greenColor];
    // 必须设置根控制器
    self.window.rootViewController = [UIViewController new];
    [self.window makeKeyAndVisible];
}

场景2:需要适配iOS 12及以下版本,不使用SceneDelegate

  1. 先在AppDelegate.h中声明window属性:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
  1. 在didFinishLaunchingWithOptions方法中初始化window后再设置属性:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"applicationDidFinishLaunching");
    // 手动初始化window
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor greenColor];
    // 必须设置根控制器
    self.window.rootViewController = [UIViewController new];
    [self.window makeKeyAndVisible];
    return YES;
}
  1. 若完全不需要使用SceneDelegate,还需要删除项目中SceneDelegate相关文件,同时删除Info.plist中Application Scene Manifest配置项,避免iOS 13以上系统仍走SceneDelegate生命周期。

内容的提问来源于stack exchange,提问作者stefanosn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:06:03