I first created a property in my SecondViewController.h file using
@property (weak, nonatomic) IBOutlet UIWebView *webView;
And then synthesised it in the corresponding .m file using
@property (weak, nonatomic) IBOutlet UIWebView *webView;
I then created a function to create a webpage using a string which the user would cast as an argument. The function:
void createWebpage(NSString *webString) {
NSURL *url = [NSURL URLWithString:webString];
NSURLRequest *requestUrl = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestUrl];
}
And where it is called.
- (void)viewDidLoad {
createWebpage(@"http://www.google.com");
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
However, in the last line of the function, [webView loadRequest:requestUrl];
, webView produces the error "Use of undeclared identifier 'webView'. Why is this, and how can I fix it? All help appreciated.
You are declaring a property which is a available in an object. But you are declaring a simple C method:
void createWebpage(NSString *webString) {
NSURL *url = [NSURL URLWithString:webString];
NSURLRequest *requestUrl = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestUrl];
}
This method will be executed in a "global context" but not on the object. So you can't access the objects properties.
Instead use a method:
- (void) createWebpage:(NSString *)webString {
NSURL *url = [NSURL URLWithString:webString];
NSURLRequest *requestUrl = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestUrl];
}
And you have to use self
to refer to the current object when you're accessing a property.
You can then call this method:
[self createWebpage:@"http://www.google.com"];
I really recommend you to read this: https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html
void createWebpage
is not a instance method, so the instance variables (such as webView
) won't be accessible from there.
You must declare the method as: -(void)createWebpage:(NSString *)webString
, and call it as [self createWebPage:@"http://www.google.com"];