Objective-C 中未调用重写 setter
我正在调试示例教程片段,并对设置器的重写感到困惑。
我声明并重写如下所示:
//
// PolygonShape.h
//
@interface PolygonShape : NSObject
{
int numberOfSides;
}
@property int numberOfSides;
//
// PolygonShape.m
//
@synthesize numberOfSides;
// custom setter.
- (void) setnumberOfSides:(int) i
{
if ((i > minimumNumberOfSides) && (i <= maximumNumberOfSides))
numberOfSides = i;
else
NSLog (@"Number of sides outside limits:\n You entered %d, limits are min.:%d, max.:%d",
i, minimumNumberOfSides+1, maximumNumberOfSides);
}
//
// main.m
//
poly = [[PolygonShape alloc] init];
poly.numberOfSides = 2;
[poly setnumberOfSides:2];
所以我在这里假设的想法是,因为我“重写”了 numberOfSides
的合成设置器,然后 poly.numberOfSides = 2 ;
会调用我的 (void) setnumberOfSides:(int) i
函数。但相反,调用该函数的唯一方法是当我显式执行 [poly setnumberOfSides:2];
时,
我不明白。那么覆盖有什么意义呢?
或者更有可能的是,我做错了什么? ;)
I'm debugging a sample tutorial snippet and am confused about the overriding of setters.
I declare and override as shown here:
//
// PolygonShape.h
//
@interface PolygonShape : NSObject
{
int numberOfSides;
}
@property int numberOfSides;
//
// PolygonShape.m
//
@synthesize numberOfSides;
// custom setter.
- (void) setnumberOfSides:(int) i
{
if ((i > minimumNumberOfSides) && (i <= maximumNumberOfSides))
numberOfSides = i;
else
NSLog (@"Number of sides outside limits:\n You entered %d, limits are min.:%d, max.:%d",
i, minimumNumberOfSides+1, maximumNumberOfSides);
}
//
// main.m
//
poly = [[PolygonShape alloc] init];
poly.numberOfSides = 2;
[poly setnumberOfSides:2];
So my assumed thought here is that, since I "override" the synthesized setter for numberOfSides
, then poly.numberOfSides = 2;
would have called my (void) setnumberOfSides:(int) i
function. But instead, the only way that function gets called is when I explicitly do [poly setnumberOfSides:2];
I don't get it. What's the point of overriding then?
Or more likely, what am I doing wrong? ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它的大小写不正确,大小写很重要。它应该是
setNumberOfSides:
。It's incorrectly capitalized, and capitalization matters. It should be
setNumberOfSides:
.