Re: Accessors
Re: Accessors
- Subject: Re: Accessors
- From: Shawn Erickson <email@hidden>
- Date: Wed, 7 Aug 2002 23:03:04 -0700
On Wednesday, August 7, 2002, at 10:04 AM, Kevin Elliott wrote:
BUT, again, that is irrelevant because you are once again relying on an
internal implementation detail of the class, which is contrary to OO
design!!!
I do understand your point and agree with it. I have been playing some
what of a devils advocate while also supporting the guidance Apple
seems to have given for things. Its hard to do... ;-)
I don't buy the thread argument in support of autorelease (it doesn't
remove the issue it just makes it less likely, locks are also needed).
I agree that the only safe thing to do is to retain an object while it
is needed. I agree that no currently documented contract really states
that an object will exist until the containing autorelease pool is
release; however, because autorelease is the main tool that exist for
doing this it generally is true (doesn't necessarily apply to a
getter). I also believe that following a defined pattern for methods
can allow optimization/assumptions to be safely made in controlled
situations (pure abstractions are great but can make optimization hard
if a pattern of expected behavior is not followed).
I do use the retain/autorelease pattern in my code to simplify the code
in other places but in controlled situations (started to doing so after
hearing Apple's recommendations). I also will call simple accessors and
do not retain/autorelease things in controlled situations (when I know
things won't get released). I do use a macro to define my common
accessors so I can easily change my accessor code around as needed
(three sets of macros actually).
One generates the following...
- (SomeType*)someName
{
return _someName;
}
- setSomeName: (SomeType*)newSomeName
{
[newSomeName retain];
[_someName release];
_someName = newSomeName;
}
Another the following...
- (SomeType*)someName
{
return _someName;
}
- setSomeName: (SomeType*)newSomeName
{
if (newSomeName == _someName) return;
[_someName release];
_someName = [newSomeName copy];
}
The last one generates set/get for things that are not objects.
In the copy case I try to avoid making unneeded copies when easily
detectable, hence the pointer comparison. If I have to deal with
threading I will use locks internally in the accessor or some times
externally to insure things are done safely (looks like mmalcolm has
this well covered in his document for those that are curious,
http://www.stepwise.com/Articles/Technical/2002-06-11.01.html/).
I hope that Apple picks a standardized pattern and applies it for all
frameworks... To be honest I do generally lean away from the use of
autorelease in accessors.
-Shawn
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.