gpt4 book ai didi

objective-c - @interface 声明和@property 声明之间的区别

转载 作者:太空狗 更新时间:2023-10-30 03:09:45 27 4
gpt4 key购买 nike

我是 C 的新手, Objective-C 的新手。对于 iPhone 子类,我在 @interface 类定义中声明我希望对类中的所有方法可见的变量,例如

@interface myclass : UIImageView {
int aVar;
}

然后我再次声明为

@property int aVar;

后来我

@synthesize aVar;

你能帮我理解这三个步骤的目的吗?我在做一些不必要的事情吗?

谢谢。

最佳答案

在这里,您要声明一个名为 aVar 的实例变量:

@interface myclass : UIImageView {
int aVar;
}

您现在可以在您的类中使用此变量:

aVar = 42;
NSLog(@"The Answer is %i.", aVar);

但是,实例变量在 Objective-C 中是私有(private)的。如果您需要其他类能够访问和/或更改 aVar 怎么办?由于方法在 Objective-C 中是公共(public)的,答案是编写一个返回 aVar 的访问器(getter)方法和一个设置 aVar 的 mutator(setter)方法:

// In header (.h) file

- (int)aVar;
- (void)setAVar:(int)newAVar;

// In implementation (.m) file

- (int)aVar {
return aVar;
}

- (void)setAVar:(int)newAVar {
if (aVar != newAVar) {
aVar = newAVar;
}
}

现在其他类可以通过以下方式获取和设置aVar:

[myclass aVar];
[myclass setAVar:24];

编写这些访问器和修改器方法可能会非常乏味,因此在 Objective-C 2.0 中,Apple 为我们简化了它。我们现在可以写:

// In header (.h) file

@property (nonatomic, assign) int aVar;

// In implementation (.m) file

@synthesize aVar;

...访问器/修改器方法将自动为我们生成。

总结:

  • int aVar;声明一个实例变量aVar

  • @property (nonatomic, assign) int aVar;aVar

  • 声明访问器和修改器方法
  • @synthesize aVar;aVar

  • 实现访问器和修改器方法

关于objective-c - @interface 声明和@property 声明之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2159725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com