loaded the "FirstView" nib but the view outlet was not set.'

這個BUG只發(fā)生在,我設置self.window.rootViewController =FirstViewController中,當我的FirstViewController不是rootViewController時,并沒有問題。

我在工程中創(chuàng)建了FirstView,由于我的FirstView控件很多,布局很復雜,所以我選擇創(chuàng)一個同名的Xib來可視化編程。


文件

代碼如下

==========AppDelegate==========
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [self setRootVC];
    [self.window makeKeyAndVisible];
    return YES;
}
- (UIViewController *)setRootVC{
    UIViewController * c = [NSClassFromString(@"FirstViewController") new];
    return c;
}

==========FirstViewController==========
@interface FirstViewController ()
@property (nonatomic,weak) FirstView *firstView;
@end

@implementation FirstViewController
-(FirstView *)firstView{
    if (!_firstView) {
        FirstView * firstView = [FirstView new];
        [self.view addSubview:firstView];
        _firstView = firstView;
    }
    return _firstView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstView.frame = CGRectMake(0, 30, 100, 100);
    self.firstView.backgroundColor =[UIColor lightGrayColor];
}

我還未往FirstView.xib中添加任何控件,也沒有加載xib的,然后運行,結果:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "FirstView" nib but the view outlet was not set.'

百思不得其解,應該沒有錯誤啊,然后各種折騰。
再看錯誤,提示FirstView有問題,于是我創(chuàng)建類secondView來替代FirstView


這回竟然成功了!?。〉降资鞘裁辞闆r
······

思來想去,又折騰了一番,仔細再看錯誤提示:

[UIViewController _loadViewFromNibNamed:bundle:] loaded the "FirstView" nib but the view outlet was not set.'

提示我,加載ViewController時,會觸發(fā)這個方法_loadViewFromNibNamed:bundle:
這個方法就是用來加載ViewController的View的,所以,由于命名關系,我所創(chuàng)建的FirstView.xib,相當于創(chuàng)建了FirstViewController.xib,所以系統(tǒng)提示我loaded the "FirstView" nib but the view outlet was not set.'

好了,知道原因就好解決了
打開FirstView.xib,指定File's Ower為FirstViewController


然后需要我們手動接連View,并且我為FirstView.xib添加兩個label


修改FirstViewController為:

#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
    [super viewDidLoad];
  
}
@end

再次運行,問題解決。


屏幕快照 2017-11-19 下午4.50.38.png

搞開發(fā)將近一年,由于一直都是純代碼Coding,最近才嘗試可視化編程。想來這次的坑,我是遲早都會碰到的。其實我一直沒搞懂File's ower和View里需要填寫的關聯(lián)類各有什么區(qū)別,經(jīng)多這次的調(diào)試,額外的讓我明白了File's ower的作用。

以下為File's ower和View里需要填寫的關聯(lián)類的區(qū)別:
Xib的使用:設置File's Owner的Class和view的Class的區(qū)別

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容