How should I set a retained property when creating an object using alloc and init? (Without using autorelease)
With this line in the header (and the corresponding @synthesize line in the implementation):
@property(retain)UIWebView *webView;
These are the three options I have (I think):
UIWebView *tempWebView = [[UIWebView alloc] init];
[tempWebView setDelegate:self];
tempWebView.hidden = YES;
self.webView = tempWebView;
[tempWebView release];
(This one seems the best concerning memory management but it’s more lines of code and involves a stupid variable name, so a decrease in readability)
self.webView = [[UIWebView alloc] init];
[self.webView release];
[self.webView setDelegate:self];
self.webView.hidden = YES;
(This one it’s more obvious whats happening but the memory management doesn’t seem that great, also Xcode’s Analyser doesn’t like it)
webView = [[UIWebView alloc] init];
[self.webView setDelegate:self];
self.webView.hidden = YES;
(This one is the shortest, it’s more obvious than the first example whats happening. But it bypasses the setter, so should a custom implementation of the setter be implemented later it won’t work in this case)
So which example should be used, or is there a better way?
The best option, IMO, is the one you don’t like, i.e. using autorelease:
If you do not want to and want a one-liner initialization, the only option is your third one:
since all the others requires an explicit line to do an extra release.
I don’t see it as bad, especially when it belongs to the
initmethod and you don’t reassign it elsewhere without using the property, and I myself use it when it seems reasonable to me.What works really well with retained properties are convenience constructors like:
So, possibly if you really find that none of the options you listed is fine with you, you might add a category to
UIWebViewand a convenience constructor doing the autorelease job for you: