Accessor methods in Obj-C

havic

Windsurfer Nerd
Well, according to my Obj-C book, there are 3 different ways to write an accessor method to set a variables value.

One is "Retain, then release", another is "Check before change", and the last is "Autorelease old value".

Retain then release adds a retain and release command, which is supposedly bad. Check before change adds an extra if statement. Autrelease old value can cause an application crash, so its definitely off for me.

My question is how CPU intensive is it for if-else statements and retain/release?

Eg, which is going to make the biggest impact when I have a lot of accessors being used?
 
You should always retain the new value before releasing the old one. Otherwise, you might run into the problem where the old value has the only reference to the new one, and releasing it causes both to disappear; check before change won't help here, but you should check anyway, as it does speed up the case where old==new. Autorelease is just silly to use in accessors.

I would also like to point out a handy utility called Accessorizer - it allows you to select your variables in Xcode/PB, then press Command-3 to copy accessor declarations and definitions to the clipboard. It offers a wealth of configuration options for the generated accessors. Check it out.

As for your question about CPU usage: if/else generally adds about ten CPU cycles of overhead. An obj-c message call adds a few hundred cycles, not including the actual function that gets called. Don't worry about this at all - save the optimizations for when you're almost done with the program, and have done profiling with optimized builds to find out where your program spends its time. Chances are, a negligible percentage will be spent in accessors.
 
havic- personally I like "retain then release." It's shorter, so its not as easy to make a mistake plus you can understand it's purpose at a glance. By the way I have the same book.

anarchie- thanks for the cool program.
 
Mmm yeah I like retain then release as well. I was just curious as to why there was any debate over it at all, and decided that maybe retain/release was quite CPU-intensive.

Thanks for the reply anarchie.

AND IDEVGAMES IS BACK!! :D
 
Back
Top