将保留的属性设置为新创建的对象的最佳方法 [英] Best way to set a retained property to a newly created object

查看:147
本文介绍了将保留的属性设置为新创建的对象的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最好的方式来处理创建一个对象在一个保留的属性生活?我包括了几个例子。

Which is the best way to handle creating an object to live in a retained property? I've included several examples.

假设属性是:

@property (nonatomic, retain) myProperty;
@synthesize myProperty = _myProperty;

选项1:

self.myProperty = [[[MyClass alloc] init] autorelease];

选项2:

self.myProperty = [[MyClass alloc] init];
[self.myProperty release];

选项3:

_myProperty = [[MyClass alloc] init];

选项4:

MyClass *property = [[MyClass alloc] init];
self.myProperty = property;
[property release];


推荐答案

选项1: ...但是你正在使用autorelease来浪费资源。引用被添加到需要在运行循环结束时释放的项目列表...你的变量保持到那时,即使它不需要..等,我相信这个选项被使用经常...但我也相信它是懒惰和浪费。

Option 1: Acceptable... but you're wasting resources with autorelease. The reference gets added to a list of items that need to get released at the end of the run loop... your variable stays around until then even if it doesn't need to.. etc, etc. I believe this option is used frequently... but I also believe it's lazy and wasteful.

选项2:困惑。没有什么错,它本身,但我会说这是坏的形式。

Option 2: Confusing. Nothing wrong with it, per-se, but I'd say it's bad form.

选项3:可接受,但不理想。如果有自定义安装程序怎么办?等我本人只在自定义setter本身,或者,可能在一个类初始化器中使用这个表单。否则,您错过了属性的一些好处。

Option 3: Acceptable, but not ideal. What if there is a custom setter? Etc. I'd personally only use this form within a custom setter itself, or, possibly in a class initializer. Otherwise, you're missing out on some of the benefits of properties.

选项4:最好。

这篇关于将保留的属性设置为新创建的对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆