虽然这是一个非常基本的问题,但在阅读了 stackoverflow.com 上的这么多文档和问题后,我仍然存在一些疑问。
我想知道为什么要将一些实例变量声明为属性。
MYViewController.h
@interface MyViewController : UIViewController {
UIButton *btn;
NSString *name;
}
@property (nonatomic, retain) UIButton *btn;
@property (nonatomic, retain) NSString *name;
MyViewController.m
@implementation MyViewController
@synthesize btn;
-(void) viewDidLoad()
{
[btn setTitle:@"Hello" forState:UIControlstaeNormal]; //this is first way where there is no need to declare btn as property
[self.btn setTitle:@"Hello" forState:UIControlstaeNormal]; //this is second way where we do need to decalre btn as property as we are accessing it through self
//Setting value of name
name = @"abc"; //this is first way where there is no need to declare name as property
[self setName:@"abc"; //this is second way where we do need to declare name as property as we are accessing its aetter method through self
}
现在,在上面的代码中,我想知道什么时候我们可以使用 btn 变量的 getter/setter 方法而不将其声明为属性,那么需要将其声明为属性,以及设置“的值的更好方法是什么”姓名”。
我在某处读到,当您希望实例变量被我的其他类对象访问时,您应该将它们声明为实例变量。这是我们应该将它们声明为属性的唯一情况吗?
基本上我对在什么情况下将实例变量声明为属性有点困惑。
请提出建议。 提前致谢。
最佳答案
简而言之,除非您愿意,否则不必将实例变量声明为属性。 您将变量声明为属性,以便自动生成 getter 和 setter 方法。在属性声明中,您可以指定如何设置它们(保留与分配、原子与非原子)。然后,使用 @synthesize 指令生成 getter 和 setter。 因此,再次强调,使用属性的方式没有正确或错误之分。有些人从不使用它们,有些人将每个变量都作为属性。这真的取决于你。
关于objective-c - 为什么要将一些实例变量声明为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4911748/