Search code examples
iospropertiessynthesize

@property declaration without @synthesizing


I am following Big Nerd Ranch iOS Programming by Joe Conway and am kinda puzzled when I saw the following code.

WebViewController.h

#import <Foundation/Foundation.h>
@interface WebViewController : UIViewController
@property (nonatomic, readonly) UIWebView *webView;
@end

WebViewController.m

#import "WebViewController.h"

@implementation WebViewController
- (void)loadView 
{
    // Create an instance of UIWebView as large as the screen
    // Tell web view to scale web content to fit within bounds of webview 
}

- (UIWebView *)webView
{
    return (UIWebView *)[self view];
}
@end

Shouldn't one synthesize the property declared in .h file? Xcode didn't give an warning either (which it usually does when I declare a property with synthesizing).

By the way, in the book, he also mentioned

In WebViewController.h, add a property (but not an instance variable)

Doesn't declaring a property automatically generate an instance variable for you? Let me know what I missed. Thanks.


Solution

  • This is because the "webView" getter method is implemented in the .m file and because of that, "@synthesize" isn't necessary.

    If a "webView" method wasn't explictly created in code, then the compiler would complain about the property not being synthesized. Synthesizing a "read only" property, in this case, would only create a "getter" method which would do roughly the same thing you see in the code up there.

    And yes, according to the Apple docs on declared properties, it says this about "@synthesize":

    You use the @synthesize directive to tell the compiler that it should synthesize the setter and/or getter methods for a property if you do not supply them within the @implementation block. The @synthesize directive also synthesizes an appropriate instance variable if it is not otherwise declared.