直接访问实例变量时使用self-> ivar [英] Using self->ivar when accessing instance variables directly

查看:92
本文介绍了直接访问实例变量时使用self-> ivar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注意到,大多数Objective-C编码人员在直接访问实例变量时从不使用self->ivar语法.我看到的大多数示例代码都只是引用实例变量而没有self->.我认为引用一个实例变量而不弄清楚它是一个实例变量而不仅仅是当前范围的变量是相当混乱的.

I have noticed that most Objective-C coders never use the self->ivar syntax when accessing instance variables directly. Most sample code that I see simply references the instance variable without self->. I think that it is rather confusing to reference an instance variable without making clear that it is an instance variable and not simply a variable of the current scope.

我觉得我想写一些东西:

I feel like I want to write stuff like:

- (void)dealloc {
    [self->someVar release];
    [self->anotherVar release];
    [super dealloc];
}

- (void)setVar:(Foo *)newVar {
    [self->var autorelease];
    self->var = [newVar retain];
}

在很多情况下,我们甚至不需要使用访问器进行封装​​就访问实例变量,但有时我们需要在dealloc或自定义getter和setter中使用.

There aren't a whole lot of occasions when we ever even should access our instance variables without using an accessor for encapsulation, but sometimes we need to such as in dealloc, or in custom getters and setters.

我是这样做的坏人/程序员吗?不写这样的代码真的有很好的理由吗?因为这样做很不错.

Am I a bad person/programmer for doing this? Is there some really good reason for not writing code like this? Because it feels really good to do it this way.

推荐答案

Chuck是正确的,因为没有技术原因,除非您用本地方法遮盖ivars,否则不应该这样写变量,这通常是个坏主意.但是,可以说省略self->在样式上更简洁,并且肯定会减少冗长的代码.就我个人而言,我会发现self->会让人分心(特别是如果代码设计合理且变量命名正确),但如果它使您更容易理解,那就一定要这样做.请注意,如果您向其他Objective-C程序员展示代码,那么他们可能会有不同的意见,因此拥有思考的皮肤是件好事.此外,大多数程序员发现,他们对使代码感觉良好"的理解随时间和经验的变化而变化,并且这些意见通常随着年龄的增长而消失. :-)

Chuck is correct in that there's no technical reason you shouldn't write it that way, unless you're shadowing ivars with local variables, which is is generally a bad idea. However, it's arguable that omitting self-> is stylistically cleaner, and it certainly results in less verbose code. Personally I would find the self-> to be distracting (especially if the code is well-designed and variables are well-named) but if it makes things more understandable for you, by all means do it. Just be aware that if you show your code to other Objective-C programmers, they're likely to have a conflicting opinion, so it's good to have a think skin. Besides, most programmers find that their perception of what makes code "feel good" changes over time and with experience, and those opinions often mellow out with age. :-)

这篇关于直接访问实例变量时使用self-> ivar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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