views:

44

answers:

1

Hi,

I have seen this code in most of the time. Here there are two variable names defined and in the implementation it synthesizing by assigning. Whats the purpose of doing some thing like this? Like keeping 2 separate variable names. Is this sort of a convention?

Test.h

@interface Test {

  id<something> _variable1;
}

@property (nonatomic, retain)  id<something> variable2;



Test.m

@synthesize variable2 = _variable1
+5  A: 

There is only one variable. The thing named variable2 is actually a property, which is basically a syntactic shortcut for a get/set method pair. When defining a property, you can either write the get/set methods explicitly...

- (void)setVariable2:(id<something>)value {
    if (_variable1 != value) {
        [_variable1 release];
        _variable1 = [value retain];
    }
}

- (id<something>)variable2 {
    return _variable1;
}

...or use the @synthesize construct to generate the above methods automatically, thus sparing you a lot of monotonous typing. (It also emits code to release _variable1 on destruction of the object, which I haven't included here.)

Sometimes, however, you might want to implement one or other of these methods differently to the default. In this case, you would write your own. You can even mix together @synthesize and a custom version of just one of the methods.

Marcelo Cantos
Thank you for the answer Marcelo. Its really helpful.
Dilshan
-1 The setter leaks. You don't release the old value.
JeremyP
@JeremyP: Thanks for pointing that out. I've amended the answer.
Marcelo Cantos
Your setter is dangerous. The following code will crash: `test.variable2 = test.variable2`. You should either do a pointer equality test in the setter, use autorelease instead of release, or retain the new value before releasing the old.
Kevin Ballard
@Kevin: Thanks. I've learned a bit myself in the process. All the more reason to use `@synthesize` where possible. I've amended the answer (and I'm hoping I got the pointer equality test right; I'm just assuming it's the same for ids as for plain old pointers).
Marcelo Cantos
Yep, the setter looks good now. An id is in fact just a pointer, just like any other obj-c object.
Kevin Ballard
Now you have fixed the setter, I have changed my down vote to an up vote.
JeremyP
Thank you kindly, @JeremyP.
Marcelo Cantos