我什么时候需要同时拥有iVar和属性? [英] When do I need to have both iVar and a property?

查看:69
本文介绍了我什么时候需要同时拥有iVar和属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些例子有时会声明一个属性以及变量,有时它们不会.e.g。有一段时间我看到这样的代码

I see some examples sometimes would declare a property as well as variable other times they do not .e.g. some time I see code like this

@interface Test : NSObject
{
  UIProgressView* _progressView;
}
@property (nonatomic,retain)UIProgressView* progressView;

@end

在其他时候我会遇到

at other times I will come across

@interface Test : NSObject

@property (nonatomic,retain)UIProgressView* progressView;

@end

为什么原因是什么?我正在学习,几乎总是使用属性和变量。

Why what are the reasons ? I am learning and almost always use property and variable both.

我使用 UIProgressView 就像示例。

I have used UIProgressView just as example.

推荐答案

这取决于属性是针对iVar合成还是以其他方式派生(或针对另一种方式) iVar)。

It depends whether the property is synthesized against an iVar or derived in some other way (or against another iVar).

如果我们有一个类的实例 - 即:

IF we have an instance of the class - i.e:

Test *myTest = [[Test alloc] init];

然后基本上属性声明

@property (nonatomic,retain)UIProgressView* progressView;

告诉任何有兴趣使用该界面的人,他们可以在这个实例上访问以下两个函数class:

is telling anyone interested in using the interface that they can access the following two functions on an instance of this class:

[myTest progressBar];
[myTest setProgressBar:aProgressBar];

目标C还允许您使用速记符号:

And objective C also lets you use shorthand notation:

myTest.progressBar =
xxx = myTest.progressBar

完全相同。

这两种方法没有必要通过与属性同名的iVar实现,或者即使是通过iVar(他们甚至可以做数据库获取或派生值)。

It is not necessary for these two methods to be implemented via an iVar of the same name as the property, or even via an iVar at all (they could do even do a database fetch or derive the value).

如果你@synthesize属性(这意味着你希望预编译器为你生成上述方法)并且没有在@synthesize指令上显式指定iVar,然后将自动生成上述方法(由于合成方法)以设置或从与属性相同名称的iVar获取值(并且实现将包括取决于属性指令的保留/释放逻辑。

If you @synthesize the property (which means you want the precompiler to generate the above methods for you) and don't explicitly specify an iVar on the @synthesize directive, then the methods described above will automatically be generated (due to the synthesize method) to set or get the value to/from an iVar of the same name as the property (and the implementation will include retain/release logic depending on the property directive.

如果你没有@synthesize属性,那么你提供自己的实现,它可以是你想要的任何东西。也可以@synthesize属性但包含一个指令在方法定义中使用不同的iVar:

If you don't @synthesize the property then you provide your own implementation and it can be anything you want. It is also possible to @synthesize the property but include a directive to use a different iVar in the method definition:

@synthesize progressBar=someOtheriVar;

在这种情况下,您将看不到与头文件中属性同名的iVar。

in which case you will not see an iVar of the same name as the property in the header file either.

这篇关于我什么时候需要同时拥有iVar和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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