创建对象并设置保留属性
使用 alloc 和 init 创建对象时应该如何设置保留属性? (不使用 autorelease)
标题中的这一行(以及实现中相应的 @synthesize 行):
@property(retain)UIWebView *webView;
这是我拥有的三个选项(我认为):(
UIWebView *tempWebView = [[UIWebView alloc] init];
[tempWebView setDelegate:self];
tempWebView.hidden = YES;
self.webView = tempWebView;
[tempWebView release];
这似乎是关于内存的最佳选项管理,但它的代码行更多,并且涉及一个愚蠢的变量名,因此可读性下降)
self.webView = [[UIWebView alloc] init];
[self.webView release];
[self.webView setDelegate:self];
self.webView.hidden = YES;
(这个更明显发生了什么,但内存管理似乎不太好,Xcode的分析器也不喜欢它)
webView = [[UIWebView alloc] init];
[self.webView setDelegate:self];
self.webView.hidden = YES;
(这个一个是最短,它比第一个示例更明显,但它绕过了 setter,因此如果稍后实现 setter 的自定义实现,在这种情况下它将不起作用)
那么应该使用哪个示例,或者是否有更好的示例。方式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,最好的选择是您不喜欢的选择,即使用自动释放:
如果您不想并且想要单行初始化,唯一的选择是您的第三个选择:
因为所有其他选择都需要显式行来进行额外的发布。
我不认为它很糟糕,特别是当它属于
init
方法并且您在不使用该属性的情况下不会在其他地方重新分配它时,而且我自己在我认为合理的情况下使用它。对于保留属性真正有效的是便利构造函数,例如:
因此,如果您确实发现列出的选项都不适合您,则可能会向
UIWebView
添加一个类别,并添加一个便利构造函数适合您的自动释放工作: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
init
method 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
UIWebView
and a convenience constructor doing the autorelease job for you: