views:

35

answers:

2

I have the following code for a property whose getter/setter I write manually using the @dynamic keyword:

@property (nonatomic, retain) NSObject* obj;

@dynamic obj;
-(NSObject*) obj
{
    return obj;
}
-(void) setObj:(NSObject*)newObj
{
    [obj release];
    obj = [newObj retain];
}

My question is, if I remove the retain from the @property declaration, the compiler complains that the default will be assign and that it may not be what I want. If I add the retain, I assume it is going to be ignored, because I wrote the getters/setters myself?

Just looking for a quick confirmation on this.

A: 

The retain allows your object to stay allocated in memory until you apply

[obj release];

so even if you do have your own setter and getter you need to keep the retain to keep your place in memory, because in the end you only have a pointer to that position and that is why the compiler tels you that you may modifying another object or what ever takes the place of your object.

And its important that you make the release to free the memory when you are done using it.

mklfarha
This isn't what he was asking about. He isn't asking "Should I retain in my custom setter?" He's asking, "Should the property declaration say 'retain' if I have a custom setter that retains?"
Chuck
+2  A: 

You are correct, but your property declaration is as much for documentation as it is for your implementation, at least in this case. At some point, someone (you in six months?) will look at your .h file and say, "Why isn't this value being retained? How does this not crash every time it gets run or leak memory like a sieve?"

Robot K
I do other things in the setter but I removed that for clarity.
GamingHorror