Objective C Calling Method on Another Class

2019-09-02 15:14发布

问题:

I have 2 classes, MainViewController and 'FooView' for example.

In MainViewController I have a method called -(void)doSearch

I'm trying to call doSearch from Foo, is see in the log "doSearch" (NSLog) but the UIWebView doesn't response.

Foo

MainViewController *mainVc = [[MainViewController alloc] init];
[mainVc doSearch];

MainViewController


- (void)doSearch {
    NSLog(@"doSearch");
    [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]];
}

myWebView is a UIWebView.

Thanks,

Guy Dor

回答1:

I think something is nil here. In Obj-C you can send messages (call methods) on a nil object without an error or exception. In your case, your MainViewController could be null in the FooView, or it is possible that something in that method is nil. For example, if have a xib file for that view controller, then it needs to be loaded with initWithNibName:bundle:. If you don't do that, then the IBOutlets will be nil (possibly the myWebView in your doSearch: method for example).



回答2:

Check if "mainVc" is not nil. You are probably falling at initializing it.



回答3:

if u create MainViewController with NIB file then u have to call like this.

  MainViewController *mainVc = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];

  [mainVc doSearch];