Re: Objective-C Instance Variable Names
Re: Objective-C Instance Variable Names
- Subject: Re: Objective-C Instance Variable Names
- From: Jens Alfke <email@hidden>
- Date: Sun, 6 Apr 2008 21:32:25 -0700
On 6 Apr '08, at 9:17 PM, Scott Andrew wrote:
You aren't supposed to EVER use direct ivar acess. Every document i
have ever read regarding ObjectiveC has always said to define
acessors.
Ummm ... for access to another object's instance data, that's true.
You should avoid the temptation to declare ivars as public and grope
them directly. But it's fine to access ivars of 'self' by name, and
most of the Obj-C code I've seen does so.
So what prefix you use on your ivars don't matter. To set m_object.
I am going to either define get/set functions or use properties.
You can't do this if your getters or setters are non-trivial. Let's
say I have a property whose value is computed lazily, a very common
design pattern:
- (NSImage*) icon {
if( ! _icon ) {
// allocate _icon and draw into it
}
return _icon;
}
You can't replace "_icon" with "self.icon" because you'd be calling
the method you're defining, leading to infinite regress and stack
overflow.
I guess you could create a separate private property (with ivar)
called "cachedIcon" and have the -icon getter act on that, but that's
starting to get silly.
I'll also re-iterate that calling getters and setters is Extremely
Expensive compared to directly accessing ivars. As in, something like
4x as much code at the call-site, and at least 10x as many cycles to
execute. (Probably more like 20x or 30x if you use the default
'atomic' style synthesized properties, which do autoreleasing and
thread synchronization.) It also defeats a number of compiler
optimizations.
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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