objective-c - 为什么要将一些实例变量声明为属性

标签 objective-c properties

虽然这是一个非常基本的问题,但在阅读了 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/

相关文章:

ios - 如何在 iOS 中将 jpg 或 png 转换为 svg?

eclipse - 无法创建带有外语字符的文件

java - 从特定位置检索属性文件

python - 属性错误: 'property' object has no attribute

python - 使 python @property 句柄 +=, -= 等

java - Servlet 中的属性文件位置

ios - 游戏场景不显示

ios - 一个ImageView如何正确显示不同大小的图片?

javascript - 如何在 UIWebview 中启用 JavaScript

objective-c - 无法在 uicollectionview、UICollectionView 的特定 indexPath.row 处设置单元格标题