在Obj-C中创建Properties,默认的Getter怎么写?

发布于 2024-12-29 22:23:30 字数 451 浏览 2 评论 0原文

我刚刚开始学习 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 技术交流群。

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

发布评论

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

评论(2

〃温暖了心ぐ 2025-01-05 22:23:30

仅当使用 xp 表示法时才会调用属性访问函数。您只需使用 p 即可访问支持该属性的实例变量(在 Objective C 中,所有成员都在作用域内具有类实例变量)。如果您确实需要,也可以通过指针引用符号 -> 进行访问。因此,这两个中的任何一个:

return p;

return self->p;

但是,您不需要在此处使用 @dynamic@synthesize 很聪明,如果您没有提供默认值,它只会创建默认值。因此,在这种情况下,请随意使用

@synthesize p;

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 just p (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:

return p;

return self->p;

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 just

@synthesize p;

Which will create the getter, but not the setter in this case.

本宫微胖 2025-01-05 22:23:30
- (int)myNumber {
    return myNumber;
}
- (int)myNumber {
    return myNumber;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文