I have an int property
@property(nonatomic) int stackTop;
and when it gets synthesized, it has a default value of 0. I want to set this default value to -1.
I tried overriding the setter method like this
@sythesize stackTop = _stackTop;
-(void)setStackTop:(int)stackTop
{
_stackTop = -1;
}
and then the initial value is -1 instead of 0, but it’s not changing when the variable stackTop changes in the program. For example, I have self.stackTop++;, but it’s not getting incremented. With the non-overriden setter method, that statement does change the value. What am I doing wrong? What’s the solution?
Set it to -1 in your designated initializer.
EDIT:
In response to your question, a designated initializer is the one initializer which must always be called when your class instance is created. It is the only place where
[super init];is called (which initializes the part of the class that you inherit from your parent class), and all other initializers must call this designated initializer in order to make sure that the class is properly setup and all default values are set, including those that you want to set.In your case, if you have no other methods that begin with
init, then you should do it in the-(id)initmethod. As some other people have shown since I posted my answer, it would look like this: