On 09/10/2009, at 8:01 PM, Matthias Arndt wrote:

While restructuring some old classes I'm uncertain about the preferred way to access instance variables within their own instance:

I tend to defines all these variables as properties and use their implicit getters / setters, but ...

1. ) ... in the designated initializer I have to access the instance variables directly, because at this moment "self" is not yet defined, is it?

2.) ... are there significant performance issues or other reasons to prefer the direct reference to (or direct assignment of) instance variables? At least the code of the setters / getters might impact the performance, but I'd sacrifice it for the sake of a consistent code.

Any comments / suggestions?


Properties and ivars are distinct things, though very often a property is implemented in terms of an ivar.

In init and dealloc, it is usual & recommended to access the ivar directly - not because self isn't defined (it is), but because at those times you are usually only concerned with setting the ivar's initial value (possibly to an object), or releasing it, without side effects.

At all other times, including when accessing from within the instance itself, you should usually use the getters/setters unless you have an explicit and clear reason not to. Using the getters and setters allows KVO to work as it should, and for deliberate side effects implemented both by the class and any subclasses to work normally. It is only if you definitely don't want these effects to operate that you should access the ivar directly (and in those cases, it makes for more readable code to have additional accessors that explain what they do, e.g. -setSomePropertyWithoutNotifying:)

There is a minor performance penalty in accessing your ivars through the accessors, but in general this is not something to be concerned about unless profiling shows it's a problem. The code will be more readable, and also allows a subclass to override an accessor to supplement or replace functionality correctly - if the base class bypasses the accessors very often subclasses will not work as might be expected. (Though on that score it would be nice if Objective-C supported the notion of private methods, though you can achieve something of the same effect using a (Private) category, which I'd also recommend).

--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to