Objective-C中的对象创建和实例化 [英] Objects creation and instantiation in objective-c

查看:90
本文介绍了Objective-C中的对象创建和实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出下面的代码段,其中blueViewController是iVar.
问:为什么不直接实例化iVar?

Given the piece of code below where blueViewController is an iVar.
Question: Why not instantiate the iVar directly?

BlueViewController *blueController = [[BlueViewController alloc]initWithNibName:@"BlueView" bundle:nil];
self.blueViewController = blueController;
[blueController release];

推荐答案

这取决于您在课堂上的位置.如果您使用init(和dealloc)方法,建议直接引用ivar,以避免在setter逻辑中产生任何副作用.因此在初始化中我会做

It depends on where you are in your class. If you are in your init (and dealloc) method it is recommended to refer to the ivar directly to avoid any side effects in setter logic. Therefore in the init I would do

_blueViewController = [[BlueViewController alloc] initWithNibName:@"BlueView" bundle:nil];

但是在其他任何地方,我都会按照您的方式去做.然后,如果getter/setter中有任何自定义逻辑,我知道它将被运行.

But anywhere else I would do it how you have done it. Then if there is any custom logic in the getter/setter I know it will be run.

要详细阐述@Vladimar的观点,保留的综合二传手将进行一些类似于以下的内存管理:

To eleborate on @Vladimar's point the synthesized setter for a retain will do some memory management similar to this:

- (void)setMyObject:(MyObject *)newMyObject
{
  // If it's the same object we don't need to do anything
  if (_myObject != newMyObject) {
    [newMyObject retain];
    [_myObject release];
    _myObject = newMyObject;
  }
}

每次设置ivars时,让吸气剂/设置者担心所有这些逻辑要安全得多.

It is much safer to let the getters/setters worry about all this logic any time you set your ivars.

这篇关于Objective-C中的对象创建和实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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