定制吸气剂和设置器 iOS 5
我想使用 ARC 重写 ObjC 类中的 getter 和 setter。
.h 文件
@property (retain, nonatomic) Season *season;
.m 文件
@synthesize season;
- (void)setSeason:(Season *)s {
self.season = s;
// do some more stuff
}
- (Season *)season {
return self.season;
}
我在这里遗漏了什么吗?
I want to override the getter and setter in my ObjC class using ARC.
.h File
@property (retain, nonatomic) Season *season;
.m File
@synthesize season;
- (void)setSeason:(Season *)s {
self.season = s;
// do some more stuff
}
- (Season *)season {
return self.season;
}
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这些是无限递归循环。那是因为
被编译器翻译成
并被
翻译成
摆脱 dot-accessor
self.
并且你的代码将是正确的。然而,由于属性
season
和变量season
共享相同的名称,这种语法可能会令人困惑(尽管 Xcode 会通过对这些实体进行不同的着色来在一定程度上减少混乱)。可以通过写入显式更改变量名称,或者更好的是完全省略
@synthesize
指令。现代 Objective-C 编译器会自动为您合成访问器方法和实例变量。Yep, those are infinite recursive loops. That's because
is translated by the compiler into
and
is translated into
Get rid of the dot-accessor
self.
and your code will be correct.This syntax, however, can be confusing given that your property
season
and your variableseason
share the same name (although Xcode will somewhat lessen the confusion by coloring those entities differently). It is possible to explicitly change your variable name by writingor, better yet, omit the
@synthesize
directive altogether. The modern Objective-C compiler will automatically synthesize the accessor methods and the instance variable for you.如果您要实现自己的 getter 和 setter,则需要维护一个内部变量:
If you are going to implement your own getter and setter, you'll need to maintain an internal variable:
您缺少的是 Objective-C 编译器基本上将 self.foo = bar 语法转换为 [self setFoo:bar] 和 self. foo 转换为
[self foo]
。当前实现的您的方法正在调用自身。正如 Jeremy 所建议的,您需要实现它们,以便 setter 实际上将其调用的值分配给类上的实例变量,而 getter 返回该实例变量的值。The thing you’re missing is that the Objective-C compiler basically turns the
self.foo = bar
syntax into[self setFoo:bar]
, andself.foo
into[self foo]
. Your methods, as currently implemented, are calling themselves. As Jeremy suggests, you need to implement them such that the setter actually assigns the value it’s called with to an instance variable on your class and the getter returns the value of that instance variable.