繁体   English   中英

loadview被称为无限次

[英]loadview getting called infinite times

我的应用程序ViewController1.mViewController2.m有两个ViewController2.m

AppDelegate我有这个代码。

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
    self.viewController = [[ViewController1 alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
}
else
{
    self.viewController = [[ViewController1 alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
}


self.window.rootViewController = self.viewController;

[self.window makeKeyAndVisible];

在ViewController1.m中我添加了一个按钮,然后在按钮上单击我正在显示另一个视图控制器ViewController2.m如下所示:

ViewController2 * obj = [[ViewController2 alloc] initWithNibName:nil bundle:nil];

[self.view addSubview:obj.view];

在ViewController2.m的loadView ,我添加了另一个这样的按钮

NSLog(@"\n Load view called");

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[button addTarget:self action:@selector(onButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

[button setTitle:@"Back to previous view" forState:UIControlStateNormal];

button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);

[self.view addSubview:button];

当我运行我的应用程序时,单击ViewController1.m中的按钮,应用程序挂起并且ViewController2.m的loadView开始无限调用。

我不知道这个问题背后的原因,我只想在点击按钮上加载另一个ViewController而我没有使用任何导航控制器。

有人能指出这个问题背后的原因吗?

不要在loadView执行此操作。 而是将您的代码移动到viewDidLoad 问题是你所访问self.viewloadView ,基本要求loadView因为初始呼叫loadView再也没有回来。

对不起绕口令...当视图尚未实例化时,会自动调用loadView 仅在返回时才进行视图初始化。 如果它没有返回并且您尝试访问view属性,它将再次调用它。 在你的情况下,它是递归的,因为你仍然在loadView方法中。

来自文档

视图控制器在请求其view属性但当前为nil时调用此方法。 此方法加载或创建视图并将其分配给view属性。

当您使用initWithNibName请不要使用loadView 这是一个错误的设计。 如果您不想使用viewDidLoad并想要初始化阶段的某些内容,则覆盖此方法,

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // write your init code here.
    }
    return self;
}

loadView的专有工作是设置viewControllers视图属性。 这可能是这样的

self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];

想象一下,你的view属性的getter看起来像这样:

 if(!_view)
     [self loadView];

  return _view;

这意味着如果在设置视图之前使用self.view(如在loadView中),则会反复调用loadView。 我的建议通常是避免重写loadView,而是创建一个从awakeFromNibinitWithNib...调用的简单configureView方法initWithNib...这样可以从storyboard或nib中正确创建视图,或者通过代码实例化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM