Objective-C 中未调用重写 setter

发布于 2024-09-06 13:29:29 字数 973 浏览 5 评论 0原文

我正在调试示例教程片段,并对设置器的重写感到困惑。

我声明并重写如下所示:

//
//  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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半衾梦 2024-09-13 13:29:29

它的大小写不正确,大小写很重要。它应该是setNumberOfSides:

It's incorrectly capitalized, and capitalization matters. It should be setNumberOfSides:.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文