【问题标题】:I alloc a viewcontroller without init , but why everything works fine我分配了一个没有 init 的视图控制器,但为什么一切正常
【发布时间】:2023-11-28 11:55:02
【问题描述】:

我在没有初始化的情况下分配了一个视图控制器,但一切正常。视图控制器中的子视图工作正常。

这里是代码。

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

【问题讨论】:

  • ViewController 真的有什么作用吗?
  • 我把ViewController.m的代码放在问题描述里了。
  • 好吧,如果我没记错的话init 主要只是初始化变量。你似乎没有任何全局的,我很确定ViewController 扩展了NSObject,所以也许你不需要打电话给init
  • @Arc676 非常感谢!
  • 它的工作原理是运气不好。不要写这样的代码。碰巧 UIViewController 及其祖先没有初始化 init 中的任何关键内容。

标签: ios objective-c uiviewcontroller init alloc


【解决方案1】:

Avi 在(他的?)评论中说得对。这是愚蠢的运气。这就像在说“我的车开了 30,000 公里,没有换油,它运行良好。为什么大家都说你必须换油?”

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

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

【讨论】:

    最近更新 更多