标记实例变量@private [英] Marking instance variables @private

查看:87
本文介绍了标记实例变量@private的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到许多Apple的接口在实例变量声明之前使用@private.为此有一个很好的设计原因吗,这是我应该做的事情吗?

解决方案

私有实例变量用于将接口与实现分开.在Objective-C中,由于类声明必须显示所有实例变量,因此需要一种防止子类访问内部实现中的子类的方法.否则,其他程序员可能会编写依赖于这些内部变量的代码,这将使类设计人员无法在不破坏现有代码的情况下对类内部进行更改.

换一种说法,未标记为私有的实例变量是与子类程序员签订的合同的一部分,而标记为私有的实例变量则不是.

这意味着实例变量通常应标记为私有,以便只能通过其访问器方法进行访问(如果有的话).否则,有人可以轻松地编写您的类的子类,并只需创建一个访问器即可将任何实例变量公开.

I've noticed that a lot of Apple's interfaces use @private before their instance variable declarations. Is there a good design reason for this, and is it something I should do?

解决方案

Private instance variables are used to separate interface from implementation. In Objective-C, since the class declaration must show all of the instance variables, there needs to be a way to prevent subclasses from accessing the ones that are part of the internal implementation. Otherwise, other programmers could write code that depends on those internal variables, which would make it impossible for the class designer to make changes to the class internals without breaking existing code.

Looking at it another way, the instance variables that are not marked private are part of a contract with the subclass programmer, whereas the ones marked private are not.

This means that instance variables should usually be marked private so that they can only be accessed through their accessor methods, if at all. Otherwise, someone could easily write a subclass of your class, and simply create an accessor to make any instance variable public.

这篇关于标记实例变量@private的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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