Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

properties - In Objective-C on iOS, what is the (style) difference between "self.foo" and "foo" when using synthesized getters?

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.

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.

My arguments for the former are as follows:

  1. self.soundEffects tells every other coder working on the code that this is an iVar, not a locally scoped variable.

  2. If we ever needed to, we could put custom logic in the soundEffects getter accessor.

  3. For no concrete reason, it "feels" like the right thing to do after working in Obj-C for a year.

He accepts arguments #1 and #2 as valid, but also gives the counterpoint:

  1. Isn't this just code bloat?

  2. Shouldn't a class be allowed to talk to its own iVars directly without having to call a method (the getter) on itself?

Any takers?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have personally settled on using an underscore prefix for ivars, and this kind of synthesize

@synthesize name = _name;

That way I don't mix them up. The major issue with not using self is that this code

_name = ...

is very different from

self.name = ...

When the @property uses the retain option. The first does not retain the object, and the second calls the synthesized setter that retains.

The only time it makes a big difference is with assigning, so I tend to use self. all of the time so I make sure I do it on assigns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...