类扩展中声明的私有变量和属性的区别 [英] Difference of private variable and property declared in class extension

查看:34
本文介绍了类扩展中声明的私有变量和属性的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Objective-C 的新手,我看到了一些开源代码,如下所示:

I'm new to Objective-C, and I saw some open sourced code like below:

DetailedViewController.m:

@interface DetailedViewController()
@property(nonatomic, strong) UITableView *dynamicTable;
@end

@implementation DetailedViewControll
-(void)viewDidLoad
{
    [super viewDidLoad];
    self.dynamicTable=[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    //configure dynamicTable

}
@end

如果我声明 dynamicTable 变量并按如下方式使用它:

if I declare the dynamicTable variable and use it as below:

@interface DetailedViewController()
{
    // private tableview variable
    UITableView *dynamicTable;
}

@end

@implementation DetailedViewControll
-(void)viewDidLoad
{
    [super viewDidLoad];
    dynamicTable=[[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    //configure dynamicTable

}
@end   

我觉得上面两种使用dynamicTable变量的方式是一样的,对吗?
如果不是,使用属性是否比使用私有变量更好?

I think the the above two ways of using dynamicTable variable are equal, Am I right?
if not, Does using property is better than using private variable?

推荐答案

访问变量比访问属性更快.但是,属性为您提供了一些优势,例如键值观察(另一个对象或您的对象可以注册以在有人更改属性值时收到通知).使用哪个取决于品味和用例.

Accessing a variable is faster than accessing a property. However, a property gives you some advantages like key-value observing (another object or your object can register to be notified once someone changes the value of the property). Which one to use is a matter of taste and use-case.

如果您在公共 .h 文件中声明一个属性,则其他对象可以访问它.如果你在你的公共 .h 文件中声明你的变量,其他对象也可以访问它(object->variable),但这非常非常糟糕,不要这样做.

If you declare a property in your public .h file, other objects can access it. If you declare your variable in your public .h file, other objects can access it as well (object->variable) but this very, very bad, don't do that.

所以严格来说,你的两个例子是不相等的.然而,它们相似.很多时候,你使用哪一个并不重要.使用更适合您的那个.变量访问速度更快这一事实并不是选择一个而不是另一个的充分理由,除非您测量并且知道某个属性会导致性能问题(我还没有看到这一点,并且我正在工作在需要快速的多媒体应用上).

So strictly speaking, your two examples are not equal. They are, however, similar. Quite often it doesn't really matter which one you use. Use whichever suits you more. The fact that variable access is faster is not a good reason to chose one over the other except if you measured and know that a property is causing a performance problem (I have yet to see that, and I work on multimedia apps that need to be fast).

这篇关于类扩展中声明的私有变量和属性的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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