为什么我应该直接从初始化方法中访问实例变量? [英] Why I should access the instance variable directly from within an initialization method?

查看:169
本文介绍了为什么我应该直接从初始化方法中访问实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple 使用Objective-C编程文档声明:

The Apple Programming with Objective-C document states that:


你应该总是直接从
中初始化方法访问实例变量,因为在设置属性时,对象的
其余部分可能尚未完全初始化。即使您
不提供自定义访问器方法或知道您自己的类中
的任何副作用,未来的子类也可以很好地覆盖
行为。

You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.

但是我不知道setter方法会有什么副作用,请举个例子来解释为什么我必须直接从中访问实例变量在初始化方法中

But I don't know what side effects will be in a setter method, please give me a example to explain why I have to access the instance variable directly from within an initialization method

推荐答案

答案很简单 - 它是代码味道。 Objective-C中的 self.foobar = something 之类的点符号只是消息传递的语法糖。
发送消息到 self 通常没问题。但是有两种情况需要避免它们:

1。创建对象时,

2。当物体被摧毁时。

在这两次中,对象处于奇怪的中间状态。它缺乏诚信。在这些时间调用方法是代码味道,因为每个方法都应该在对象上操作时保持不变量。

The answer is simple - it is code smell. Dot notation like self.foobar = something in Objective-C is just a syntactic sugar for messaging. Sending messages to self is normally fine. But there are two cases you need to avoid them:

1. When the object is being created, and

2. When the object is being destroyed.

At these two times, the object is in a strange in-between state. It lacks integrity. Calling methods during these times is a code smell because every method should maintain invariants as it operates on the object.

这篇关于为什么我应该直接从初始化方法中访问实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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