自定义 Getter & Setter iOS 5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8730816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom Getter & Setter iOS 5
提问by alex
I want to override the getter and setter in my ObjC class using ARC.
我想使用 ARC 覆盖 ObjC 类中的 getter 和 setter。
.h File
.h 文件
@property (retain, nonatomic) Season *season;
.m File
.m 文件
@synthesize season;
- (void)setSeason:(Season *)s {
self.season = s;
// do some more stuff
}
- (Season *)season {
return self.season;
}
Am I missing something here?
我在这里错过了什么吗?
回答by jlehr
Yep, those are infinite recursive loops. That's because
是的,那些是无限递归循环。那是因为
self.season = s;
is translated by the compiler into
被编译器翻译成
[self setSeason:s];
and
和
return self.season;
is translated into
被翻译成
return [self season];
Get rid of the dot-accessorself.
and your code will be correct.
摆脱点访问器self.
,您的代码将是正确的。
This syntax, however, can be confusing given that your property season
and your variable season
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 writing
然而,鉴于您的属性season
和您的变量season
共享相同的名称,这种语法可能会令人困惑(尽管 Xcode 会通过对这些实体进行不同的着色而在一定程度上减少混淆)。可以通过编写显式更改变量名称
@synthesize season = _season;
or, better yet, omit the @synthesize
directive altogether. The modern Objective-C compiler will automatically synthesize the accessor methods and the instance variable for you.
或者,更好的是,@synthesize
完全省略指令。现代的 Objective-C 编译器会自动为你合成访问器方法和实例变量。
回答by Jeremy
If you are going to implement your own getter and setter, you'll need to maintain an internal variable:
如果您要实现自己的 getter 和 setter,则需要维护一个内部变量:
@synthesize season = _season;
- (void)setSeason:(Season *)s {
// set _season
//Note, if you want to retain (as opposed to assign or copy), it should look someting like this
//[_season release];
//_season = [s retain];
}
- (Season *)season {
// return _season
}
回答by Noah Witherspoon
The thing you're missing is that the Objective-C compiler basically turns the self.foo = bar
syntax into [self setFoo:bar]
, and self.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.
你失踪的事情是,Objective-C的编译器基本上变成了self.foo = bar
语法进入[self setFoo:bar]
,并self.foo
进入[self foo]
。您当前实现的方法正在调用自己。正如 Jeremy 建议的那样,您需要实现它们,以便 setter 实际上将调用它的值分配给您类上的实例变量,而 getter 返回该实例变量的值。