2015-11-08 63 views
0

我分配一個viewcontroller沒有初始化它,但一切工作正常。 viewcontroller中的子視圖工作正常。我分配一個viewcontroller沒有初始化,但爲什麼一切正常

這是代碼。

self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; 
[self.window makeKeyAndVisible]; 
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ViewController alloc]]; 

中的代碼ViewController.m

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    [self test]; 
} 


- (void)test 
{ 
    self.view.backgroundColor = [UIColor whiteColor]; 
    CGRect frame = CGRectMake(50, 100, 200, 200); 
    UIScrollView *scrollView= [[UIScrollView alloc] initWithFrame:frame]; 
    [self.view addSubview:scrollView]; 
    frame= CGRectMake(0, 0, 500, 500); 
    UIImageView *myImageView= [[UIImageView alloc] initWithFrame:frame]; 
    [scrollView addSubview:myImageView]; 
    scrollView.contentSize = CGSizeMake(500,500); 

    scrollView.backgroundColor = [UIColor blackColor]; 
    myImageView.backgroundColor = [UIColor yellowColor]; 

    scrollView.contentOffset = CGPointMake(0, 0); 

} 


@end 
+0

'ViewController'實際上做了什麼嗎? – Arc676

+0

我將ViewController.m的代碼放在問題描述中。 – Zentopia

+0

那麼,如果我沒有記錯'init'主要是初始化變量。你似乎沒有任何全局的,我非常肯定'ViewController'擴展了'NSObject',所以你可能不需要調用'init'。 – Arc676

回答

0

阿維這樣做是正確的(他?)的評論。這是愚蠢的運氣。這就像是說:「我一直在開着車行駛3萬公里而不換油,而且運行良好,爲什麼每個人都說你必須換油?」

初始化爲類設置,它是祖先類。可以肯定的是,有些設置還沒有完成,將來會導致問題。

創建對象的正確方法是使用alloc/init。如果你不這樣做,「結果是不確定的。」

+0

非常感謝! – Zentopia

相關問題