使用属性与不访问ivars之间的区别 [英] Difference between using properties and not for accessing ivars

查看:120
本文介绍了使用属性与不访问ivars之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用属性或直接访问ivars的特定性能和行为差异。

Specific performance and behaviour difference using properties or accessing the ivars directly.

对于全局变量,使用它有什么区别:

For Global variables, What is the difference between using this:

@interface myClass (){

    UIImageView *myView;
}

-(void)loadView{

  [super loadView];
  myView = [[UIImageView alloc] initWithFrame:CGrectMake(0,0,100,100)];
}

这样做:

    @interface myClass (){

    }

    @property (nonatomic, strong) UIImageView *myView; 

@synthesize myView = _myView;

    -(void)loadView{

    [super loadView];
    myView = [[UIImageView alloc] initWithFrame:CGrectMake(0,0,100,100)];
    }

每种方法都有什么好处?
建议总是使用属性的原因是什么?

What benefits can we have with every approach? What are the reasons to recommend to always uses properties?

推荐答案

在第一种情况下,你的实例变量(或ivar) myView 是该类的私有,并且不能被其他类访问。​​

In the first case, your instance variable (or ivar) myView is private to the class and cannot be accessed by another class.

在第二种情况下,你提供了一个属性,允许其他类通过合成访问器访问您的ivar。声明属性的替代方法是编写自己的访问器方法。 @synthesize 表示法适用于您。

In the second case, you have provided a property that allows other classes to access your ivar via synthesized accessors. The alternative to declared properties is to write your own accessor methods. The @synthesize notation does that for you.

请参阅声明的属性

这篇关于使用属性与不访问ivars之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆