【问题标题】:iPhone - self.view is nil in initWithNibName subclass, and viewDidLoad not callediPhone - self.view 在 initWithNibName 子类中为零,并且未调用 viewDidLoad
【发布时间】:2012-08-07 21:44:40
【问题描述】:

我有这个级联:

应用中的某处

- (void) go
{
    MyCustomViewController* controller = [[MyCustomViewController alloc] init];
    controller.delegate = self;
    [controller run];
}

在 MyCustomViewController 中

- (id) init
{
    // there is an if statement here in real to choose another XIB if needed
    // but I only display here the code that is called in my tests
    self = [super initWithNibName:@"MyXIB" bundle:nil];
    if (!self) return nil;

    self.delegate = nil;

    return self;
}

- (void) run
{
    // do things with self.view
}

MyCustomViewController 继承 GenericWindowController

在 GenericWindowController 中

/*- (id) initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    if (!(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) return nil;

    self.view.userInteractionEnabled = NO;  // THE APP CRASHES HERE ! self.view is nil

    ...

    return self;
}*/

// METHOD created following first answers : NOT CALLED
- (void) viewDidLoad
{
    self.view.userInteractionEnabled = NO;
    // and many other things done with self.view
}

MyXIB 的文件所有者设置为 MyCustomViewController,并且视图已连接。
所有文件都包含并签入到项目中。

GenericWindowController 旨在制作一些标准的东西。
MyCustomViewController 扩展了这些东西以使用 MyXIB 中设计的自定义视图。

为什么 self.view 在 GenericWindowController 中为零?
为什么不调用viewDidLoad

【问题讨论】:

    标签: iphone ios uiview uiviewcontroller viewdidload


    【解决方案1】:

    视图控制器不应尝试访问其在initWithNibName:bundle: 中的视图。应该等到viewDidLoad

    【讨论】:

    • 谢谢,我错过了,因为使用了一个有效的旧代码......奇怪。确实,在超类和子类中都没有调用 viewDidLoad...
    • 我编辑了这个问题。如何确保在调用 run 时初始化视图?我的意思是,在 viewDidLoad 中运行的代码(应该只运行一次)不会在这种方法中调用,因为它没有被调用。我该怎么做?
    • 好吧,我已经覆盖了 loadView 以确保它被调用,并且它被调用了。但是假设文档,如果调用 loadView,那么应该调用 viewDidLoad。但事实并非如此。你明白为什么了吗?
    【解决方案2】:

    self.view 仅在viewDidLoad 之后有效——在init... 中仍然是nil

    【讨论】:

      【解决方案3】:

      不可思议!!!问题是因为 XIB 缺少本地化。添加了本地化,没有问题了。

      【讨论】:

      • @TylerPfaff:我的应用程序已本地化,并且缺少一个本地化文件,即使由于设备配置而未使用也是如此。我刚加回来,没有问题了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多