开发者

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 开发者_StackOverflowfor 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


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;
    }
}


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜