我应该在Objective-C中始终使用访问器作为实例变量吗? [英] Should I always use accessors for instance variables in Objective-C?

查看:75
本文介绍了我应该在Objective-C中始终使用访问器作为实例变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含一些IBOutlet的类,那么为这些类创建访问器似乎有点愚蠢.

If I have a class with some IBOutlets, it seems kind of silly to create accessors for these.

但是然后我觉得我不总是通过实例变量的访问器来破坏OO实践.

But then I feel like I'm breaking OO practices by not always going through the accessors for instance variables.

对于一些不应该公开的实例变量,我也有相同的看法,我宁愿不公开某些类的内部工作原理.我可以将实际的ivars设为私有,但是@property速记似乎无法指定可见性.这导致我不创建访问器,而直接访问ivars.我不确定这是否会被皱眉.是吗?

I also feel the same way about some instance variables that should not be public, I'd rather not expose the inner workings of some classes. I can make the actual ivars private but the @property shorthand doesn't seem to be able to specify visibility. This leads me to not create accessors and just access the ivars directly. I'm not sure if this is frowned upon though. Is it?

对于这个公认的新手问题,社区有何想法? (请忽略点语法)

What's the community's thoughts on this admittedly newbie question? (Please ignore dot syntax)

推荐答案

我不确定直接访问实例变量,我认为不应该这样做,但是对于某些变量,使用访问器根本没有意义.就像您提到的IBOutlet一样.

I'm not sure about accessing instance variables directly, I think one shouldn't, but for some variables it just doesn't make sense to use accessors. Like for the IBOutlets you mentioned.

我只能为您提供私人访问者的帮助.从Objective-C 2.0开始,您可以

I can only help you out with private accessors. Starting with Objective-C 2.0 you can declare extensions.

类扩展名类似于匿名" 类别,但方法 他们声明必须在 主@implementation块 相应的类.

Class extensions are like "anonymous" categories, except that the methods they declare must be implemented in the main @implementation block for the corresponding class.

只需将此扩展名放入单独的头文件中,您将拥有在头文件中不可见的私有访问器.

Just put this extension into a separate header file and you'll have private accessors that aren't visible in the header.

这篇关于我应该在Objective-C中始终使用访问器作为实例变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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