Recently some example from Apple looks something like this:
@interface ViewController : UIViewController
{
**// Notice no more ivar here.**
}
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@end
@implementation ViewController
@synthesize webView = _web开发者_开发问答View;
...
- (void)dealloc
{
[_webView release];
[super dealloc];
}
My question is why aliasing the webView
to _webView
, and release in the dealloc
since there is no ivar named _webView
?
One more question, if I declare a property that has no related ivar, do I need to release it in dealloc
?
When you @synthesize
a property that doesn't have an associated ivar (whether you say @synthesize property
or @synthesize property=_property
), an ivar is generated for you. The default is to use the same name for the ivar as the property itself. If the property is a retain
property, then you have to release
the object in -dealloc
or you'll have a memory leak.
Apple's convention is to name ivars (whether declared explicitly in the interface or implicitly in an @synthesize
) with an underbar to indicate the private nature of the ivar. IMO it's also helpful to ensure that people use the ivar only when they intend to (since for some coders it seems to be easy to accidentally type myproperty
when you mean self.myproperty
, which can create significant bugs).
The answer to your last question is basically yes, though technically the answer is 'sometimes'. You only have to release the object if there is an object stored in an ivar that was retained. That's most of the time. However, properties are just a shortcut for invoking methods named 'myproperty' and 'setMyproperty' (etc), so it's possible to have a pair of methods with those names and an associated property that doesn't actually have an ivar paired with it. But if you're declaring properties with the retain
attribute and synthesizing them, you should always release the objects their ivars point to.
I think Use of properties by Xcode 4 templates will explain this better and more in detail than I could.
精彩评论