用代码创建一个空的工程

   如何用代码创建一个空的工程?

   首先删除掉自带的ViewController类、Main.storyboard和Target-Deployment Target-Main Interface(删除“Main”),然后在AppDelegate.m的didFinishLaunch中进行_window的实例化和显示操作。此时程序执行到didFinishLaunch方法时,self.window仍为nil,并没有被实例化。

  如果进删除ViewController类、不删除Main.storyboard,程序照样正常启动;程序执行到didFinishLaunch方法时,_window已初始化完成,因为程序将storyboard中的viewController实例化,并赋给_window; 此时再在AppDelegate.m中写如下代码,[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];就会再新创建一个window再次赋值给self.window。原来加载了storyboard中VC的window就会被销毁。

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 通过打断点看出,在此之前self.window = nil;
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor]; //屏幕显示的是self.window的白色
    
    UIViewController *rootVC = [[UIViewController alloc]init];
    self.window.rootViewController = rootVC; //rootVC.view = nil;是一片漆黑

    
    [self.window makeKeyAndVisible];
    
    return YES;
}

今日突发奇想,能不能通过覆写AppDelegate类的初始化方法来创建一个空的工程呢?于是作如下操作:

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

//通过重写AppDelegate类的init方法来创建空的工程虽然也可以,但是不够安全。因为我们并不知道AppDelegate类在init方法中做了哪些操作,冒然去覆写init方法,可能会导致错误。

- (instancetype)init{
    
    self = [super init]; //父类super是UIResponder
    if (self) {
        
        self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
        self.window.backgroundColor = [UIColor whiteColor];
 
         UIViewController *rootVC = [[UIViewController alloc]init];
         self.window.rootViewController = rootVC; //rootVC.view = nil;是一片漆黑

 
        [self.window makeKeyAndVisible];
    }
    
    return self;
}

结论是:通过重写AppDelegate类的init方法来创建空的工程也是可以的,效果和第一种做法一样。但是还是不建议这么做,总感觉不够安全。 因为我们并不知道AppDelegate类在init方法中做了哪些操作,冒然去覆写init方法,可能会导致错误。

iOS开发者交流群:180080550
原文地址:https://www.cnblogs.com/stevenwuzheng/p/5395788.html