silk song silk song - 5 months ago 32
iOS Question

Basic Objective C grammar

I am learning iOS development. In a setter method, I do not know the grammar and its function.

-(void)setURL:(NSURL *)URL
{
_URL = URL;
if(_URL) {
NSURLRequest *req = NSURLRequest requestWithURL:_URL];
[(UIWebView *)self.view loadRequest:req];
}
}


All I don't understand is that line:

[(UIWebView *)self.view loadRequest:req];


It is my first time to meet that situation:indicate self as a pointer to a UIWebView instance? or indicate self.view as a pointer to a UIWebView instance? If the latter, it quite makes sense. In my application, self is a instance of UIViewController, and its view property is a UIWebView. But what is the point to add it? Why not just use self.view instead? Thanks for help

Jim Jim
Answer

It's manually telling the compiler that self.view is of type UIWebView * – this is known as typecasting. UIViewController's view property is defined to be UIView *. This class doesn't have any method loadRequest:, so if you try to call it without casting the object to UIWebView *, then the compiler will warn you that you appear to be doing something incorrect.