为BOOL变量写入getter和setter [英] Writing getter and setter for BOOL variable
问题描述
显然,使用obj-c,通常没有理由写getter和setter(感谢有用的mr @synthesize
)。
现在,需要做到这一点,我遇到了问题,我不知道如何写他们。 :p
我相信我可能不会以正确的方式解决我的问题 - 它会更容易子类化我的对象等 - 但我因为(一开始)它更快,而且我想学习如何在我的应用程序中使用类别代码。
我有这个:
- (BOOL)isMethodStep {
return self.isMethodStep;
}
- (void)setIsMethodStep:(BOOL)theBoolean {
if(self.isMethodStep!= theBoolean){
self.isMethodStep = theBoolean;
}
}
安装者,但似乎都不工作。使用断点加载它显示,由于某种原因,它会在getter方法中被阻塞在一个连续的循环中。
这段代码是正确的还是我做错了? >
感谢
Tom
$ b
- (BOOL)isMethodStep {
return self.isMethodStep;
}
return self.isMethodStep
;调用相同的 isMethodStep
方法导致无限循环。同样的事情为setter。
只需在您的访问器方法实现中直接使用您的iVars:
- (BOOL)isMethodStep {
return isMethodStep;
}
- (void)setIsMethodStep:(BOOL)theBoolean {
if(isMethodStep!= theBoolean){
isMethodStep = theBoolean;
}
}
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
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;
}
}
这篇关于为BOOL变量写入getter和setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!