开发者

load webview content in the initializer

This is an iPad app. You press one of two buttons and it presents a modal view controller containing a webview which will display a PDF. I created the UIViewController class containing the webview, and I want to use 1 of 2 initializers depending on which button the user pushes. When I initial开发者_运维知识库ize the object I want to set which PDF is displayed. The modal view is coming up but it is blank(No PDF displayed). However, when I use this same code within -(void)viewDidLoad{} it does work. Why is this? Thanks!

 - (id)initAsPi{
    NSLog(@"initAsPi Called");
    [super init];
    NSString *urlAddress = [[NSBundle mainBundle] pathForResource:@"PiPdf" ofType:@"pdf"];
    NSURL *url = [NSURL fileURLWithPath:urlAddress];
    NSURLRequest *urlRequestObj = [NSURLRequest requestWithURL:url];
    [prescribingInfoWebView loadRequest:urlRequestObj];
    return self;
    }


Initialization

Your initialization method is wrong. Read Implementing an Initializer - Handling Initialization Failure at ...

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html%23//apple_ref/doc/uid/TP30001163-CH22-105377

It should look like ...

- (id)initAsPi {
  self = [super init];
  if ( self ) {
    // Your initialization code
  }
  return self;
}

Why it does work in viewDidLoad and not in initAsPi?

prescribingInfoWebView is nil unless you're doing something obscure elsewhere.

You're probably creating prescribingInfoWebView in loadView method or it is automatically initialized during view load if you're loading your view from XIB.


When the init method of a view controller is executed, it has not yet loaded its view. So prescribingInfoWebView is probably nil at this point (you should check with the debugger) and so the message you are trying to send to it has no effect.


UIViewControllers load their interfaces lazily. This means any UI properties set up in Interface Builder or in -loadView will be nil until some request for the view causes it to load. In your initializer, this is almost certainly the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜