[Drawkit] get tool controller?

Graham Cox graham.cox at bigpond.com
Tue Feb 17 18:44:15 PST 2009


On 18 Feb 2009, at 1:26 pm, James Maxwell wrote:

> No luck yet, but I'll keep trying. This class has used mostly  
> factory methods, so I'm a bit surprised that I'm having these  
> problems (unless you know of some hidden dangers with factory methods)


Well, hard to say. "Factory method" is just a design pattern, it  
doesn't say anything about specific implementations.

However, in Cocoa, typically a factory method will return an  
autoreleased object. If you want the object to stick around, you must  
adopt ownership of it, i.e. retain it. So if you're doing something  
like:

myIvar = [FactoryClass someFactoryObject];


Then after a short time, myIvar will point to garbage, because the  
object got (correctly) autoreleased. To avoid this, just don't get  
into the habit of writing code like the above. Instead, always write  
an accessor for every property:

- (void)	setMyIvar:(id) something
{
     [something retain];
     [myIvar release];
     myIvar = something;
}

Then use it everywhere:

[self setMyIvar:[FactoryClass someFactoryObject]];

This wraps up all the memory management you ever have to do with  
'myIvar' into one method, so you can't go wrong. It no longer matters  
whether <something> is retained, autoreleased or plays the flute, it  
is managed properly. The only places that an ivar that references  
another object should ever get touched are in init, dealloc and the  
accessor method. If you are touching it anywhere else, revise that  
code for a happy life.

Because memory bugs are so hard to debug, it's well worth while just  
not taking any chances. Write accessor methods as a matter of routine  
and you'll have far fewer bugs to deal with.

--Graham




More information about the Drawkit mailing list