我没有init分配一个viewcontroller,但为什么一切正常

时间:2015-11-08 11:54:35

标签: ios objective-c uiviewcontroller init alloc

我在没有init的情况下分配一个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

1 个答案:

答案 0 :(得分:0)

Avi在(他的?)评论中说得对。这是一个愚蠢的运气。这就像说"我一直在驾驶我的汽车30,000公里而不换油,它运行良好。为什么每个人都说你必须换油?"

Init为类及其祖先类进行设置。可以肯定的是,有些设置尚未完成,将来会导致问题。

创建对象的正确方法是使用alloc / init。如果你不这样做,"结果是未定义的。"

相关问题