修改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
- 先在
AppDelegate.h中声明window属性:
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
- 在
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; }
- 若完全不需要使用SceneDelegate,还需要删除项目中SceneDelegate相关文件,同时删除Info.plist中
Application Scene Manifest配置项,避免iOS 13以上系统仍走SceneDelegate生命周期。
内容的提问来源于stack exchange,提问作者stefanosn
相关产品推荐
相关产品推荐

