Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing getter and setter for BOOL variable

Obviously, with obj-c, there's usually no reason to write getters and setters (thanks to useful mr @synthesize).

So now, needing to do just this, I've come across the problem that I don't know how to write them. :p

I'm sure I'm probably not going about solving my problem the right way - it would be much easier to just subclass my object and such - but I'm trying to write category code to add properties because (in the beginning) it was quicker, and because I wanted to learn how to use category code in my app.

I've got this:

-(BOOL)isMethodStep {
    return self.isMethodStep;
}

-(void)setIsMethodStep:(BOOL)theBoolean {
    if(self.isMethodStep != theBoolean){
        self.isMethodStep = theBoolean;
    }
}

and I've tried it without the if query in the setter, but neither seem to work. Loading it with breakpoints shows that for some reason it gets stuck in a continuous loop in the getter method.

Is this code right or am I doing something wrong?

Thanks Tom

like image 361
Thomas Clayson Avatar asked Nov 04 '10 16:11

Thomas Clayson


2 Answers

You don't want to use the self. property syntax within the setter/getter, because that invokes the setter/getter again, instead of directly assigning to the variable.

You need to just say:

-(BOOL)isMethodStep {
    return isMethodStep;
}

-(void)setIsMethodStep:(BOOL)theBoolean {
    isMethodStep = theBoolean;
}

(assuming "isMethodStep" is the name of your variable). I would omit the test in the setter method too...

like image 36
David Gelhar Avatar answered Oct 01 '22 22:10

David Gelhar


In

-(BOOL)isMethodStep {
    return self.isMethodStep;
}

return self.isMethodStep; calls the same isMethodStep method causing an infinite loop. Same thing for setter.

Just use your iVars directly in your accessor method implementations:

-(BOOL)isMethodStep {
    return isMethodStep;
}

-(void)setIsMethodStep:(BOOL)theBoolean {
    if(isMethodStep != theBoolean){
        isMethodStep = theBoolean;
    }
}
like image 138
Vladimir Avatar answered Oct 01 '22 23:10

Vladimir