在 iOS 上的 Objective-C 中,“self.foo"和“self.foo"之间的(风格)区别是什么?和“foo"何时使用合成吸气剂? [英] In Objective-C on iOS, what is the (style) difference between "self.foo" and "foo" when using synthesized getters?
问题描述
我搜索了很多关于 ObjC 访问器和合成访问器的问题,但无济于事.这个问题更像是一个帮我解决一个问题"的问题;我不期望有一个答案,但我更愿意寻找专家来讨论这个论点.
I have searched many questions on ObjC accessors and synthesized accessors to no avail. This question is more of a "help me settle an issue" question; I don't expect one answer, but I'm rather looking for experts to weigh in on the argument.
在 Cocoa Touch 类中,我会写一些这样的代码(其中 soundEffects
是合成的 NSArray 属性):
In a Cocoa Touch class, I would write some code like this (where soundEffects
is a synthesized NSArray property):
id foo = [self.soundEffects objectAtIndex:1];
一位同事让我解释为什么上面的比这条线更好:
A colleague asked me to explain why the above is any better than this line:
id foo = [soundEffects objectAtIndex:1];
嗯,在功能上,它没有什么不同.
Well, functionally, it's no different.
我对前者的论证如下:
self.soundEffects
告诉所有其他编码人员,这是一个 iVar,而不是局部范围的变量.
self.soundEffects
tells every other coder working on the code that this is an iVar, not a locally scoped variable.
如果需要,我们可以将自定义逻辑放在 soundEffects
获取器访问器中.
If we ever needed to, we could put custom logic in the soundEffects
getter accessor.
没有具体的原因,在 Obj-C 工作一年后,感觉"是正确的事情.
For no concrete reason, it "feels" like the right thing to do after working in Obj-C for a year.
他接受参数 #1 和 #2 为有效,但也给出了反驳:
He accepts arguments #1 and #2 as valid, but also gives the counterpoint:
这不就是代码膨胀吗?
Isn't this just code bloat?
难道不应该允许一个类直接与它自己的 iVar 对话而不必调用它自己的方法(getter)吗?
Shouldn't a class be allowed to talk to its own iVars directly without having to call a method (the getter) on itself?
有人接受吗?
推荐答案
您的第 1 点不太正确:self.soundEffects
不是 一个 ivar,尽管它可能碰巧给你一些是的东西——就像你合成的NSArray
一样,目前.
Your point 1 is not quite right: self.soundEffects
is not an ivar, although it may happen to give you something which is -- as it does in the case of your synthesized NSArray
, at the moment.
这反过来意味着您的第 2 点是问题的关键——如果您通过访问器路由所有访问,那么一切都被很好地封装,您以后可以自由地修改实现而不必担心副作用.
This in turn implies that your point 2 is the crux of the matter -- if you route all access through the accessor, then everything is nicely encapsulated and you're free to modify the implementation later without having to worry about side effects.
当您使用 mutator 时,这也是一个很好的做法,因此您可以保持一致的内存管理.
It's also good practice for when you use the mutator, so you maintain consistent memory management.
在大多数情况下,我认为最好通过 self.property
路由是 属性的所有内容,并限制对属于属性的直接 ivar 访问严格内部.但是,我承认在某些情况下——特别是对于不使用 retain
/copy
语义的东西——它可能更多是一种风格偏好.
For the most part, I'd say it's advisable to route through self.property
for everything that is a property, and restrict direct ivar access to things which are strictly internal. However, I'll admit that in some cases -- especially for things that don't use retain
/copy
semantics -- it can be more of a style preference.
这篇关于在 iOS 上的 Objective-C 中,“self.foo"和“self.foo"之间的(风格)区别是什么?和“foo"何时使用合成吸气剂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!