Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top