Re: accessing ivars in - (id)init
Re: accessing ivars in - (id)init
- Subject: Re: accessing ivars in - (id)init
- From: "Michael Ash" <email@hidden>
- Date: Fri, 9 Jan 2009 23:49:37 -0500
On Fri, Jan 9, 2009 at 11:07 PM, Ron Fleckner
<email@hidden> wrote:
> Hi,
>
> I read with interest the guidance in a recent thread regarding accessing
> ivars in -init methods. In a subclass of NSWindow I call [self
> setBackgroundColor:someColor] even though I don't override that method. This
> has worked in the wild for about two years, but I wanted to conform to best
> practice. I tried accessing backgroundColor directly, but the compiler won't
> let me because that ivar doesn't exist in my subclass. Calling the method
> on super works, but when I quit my app the debugger started (but failed to
> load the program after about a minute!).
>
> How should I set the background colour in this situation? Should I override
> -backgroundColor and -setBackgroundColor: or should I just keep using [self
> setBackgroundColor:aColor] in my -init?
>
> For your information, -backgroundColor and -setBackgroundColor: are declared
> in NSWindow.h
IMO the advice to avoid setters in -init and -dealloc is greatly
overblown in general. If you override your superclass's methods you
had better well expect that it might call them when it's setting up or
shutting down! Taking things to their logical conclusion, you
shouldn't call *any* public methods on yourself in either place, and I
doubt anyone follows that.
However even if you do take this advice to be useful, this is still
going way too far. Accessing your superclass's ivars directly is *far*
worse than calling a setter. The setter exists for this reason, use
it.
Note that the problems, such as they are, with calling setters only
show up if your class is subclassed and the subclass does something
weird that doesn't like being called when the rest of the subclass
isn't initialized. If you're not subclassing your own class (or you
are but you aren't doing anything weird like this in it) then you are
perfectly safe.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden