在Obj-C中创建Properties,默认的Getter怎么写?
我刚刚开始学习 Objective-C,我想要学习的一件事是良好的属性使用。我目前正在尝试使用自定义设置器创建一些属性。这就是我已经取得的进展:
@interface MyClass : NSObject
@property (nonatomic, assign) int myNumber;
@end
@implementation MyClass
@dynamic myNumber;
- (int)myNumber {
return ???;
}
- (void)setMyNumber:newNumber {
myNumber = newNumber;
// custom stuff here
}
我真的只想实现一个自定义设置器,我对默认的获取器很满意。但是,如何直接访问该变量呢?如果我输入“return self.myNumber”,那不是会调用getter方法并无限循环吗?
I'm just starting to learn Objective-C, one thing I'm trying to learn is good Property use. I'm currently trying to create some properties with custom setters. This is how far I've gotten:
@interface MyClass : NSObject
@property (nonatomic, assign) int myNumber;
@end
@implementation MyClass
@dynamic myNumber;
- (int)myNumber {
return ???;
}
- (void)setMyNumber:newNumber {
myNumber = newNumber;
// custom stuff here
}
I really just want to implement a custom setter, I'm fine with the getter being default. However, how do I access the variable directly? If I put "return self.myNumber", won't that just call the getter method and infinite loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当使用 xp 表示法时才会调用属性访问函数。您只需使用
p
即可访问支持该属性的实例变量(在 Objective C 中,所有成员都在作用域内具有类实例变量)。如果您确实需要,也可以通过指针引用符号->
进行访问。因此,这两个中的任何一个:但是,您不需要在此处使用
@dynamic
。@synthesize
很聪明,如果您没有提供默认值,它只会创建默认值。因此,在这种情况下,请随意使用Which 将创建 getter,但不会创建 setter。
Property access functions are only called when using the
x.p
notation. You can access the instance variable backing the property with justp
(in Objective C, all members have the class instance variables in scope). You can, if you really want, also access via the pointer deference notation->
. So, any of these two:However, you needn't use
@dynamic
here.@synthesize
is smart, and will only create defaults if you've not provided them. So feel free to justWhich will create the getter, but not the setter in this case.