对于obj-c中的属性,我们是否需要声明实例变量? [英] With properties in obj-c, do we need to declare the instance variables?

查看:76
本文介绍了对于obj-c中的属性,我们是否需要声明实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于obj-c中的属性,我们是否需要声明实例变量?

With properties in obj-c, do we need to declare the instance variables?

例如,如果我的.h文件如下所示:

Eg if my .h file looks like this:

@interface MyClass : NSObject {
}

@property (nonatomic, retain) NSNumber *someId;
@property (nonatomic, retain) NSDate *expires;
@property (nonatomic, retain) NSString *someString;

...

这样可以吗?它编译和工作,是完成的事情?或者我应该在下面做什么:

Is that fine? It compiles and works, is it the 'done thing' ? Or should i really be doing the below:

@interface MyClass : NSObject {
    NSNumber *someId;
    NSDate *expires;
    NSString *someString;
}

@property (nonatomic, retain) NSNumber *someId;
@property (nonatomic, retain) NSDate *expires;
@property (nonatomic, retain) NSString *someString;

...

上述任何一种方式都有任何差异,如果我打算总是使用属性访问器?

Is there any difference in either of the above ways, if i plan to always use the property accessors?

@synthesize是否负责为我创建实例变量?

Does the @synthesize take care of creating the instance vars for me?

推荐答案

您理解正确, @synthesize 负责创建 ivars 为你。 (这是运行时的一项新功能,它与64位Mac和iOS设备兼容。)

You understood correctly, @synthesize takes care of creating ivars for you. (That's a new feature of the runtime that's compatible with 64 bits Macs and iOS devices.)

有什么好处,你可以在课程扩展并将您的ivars完全隐藏在.h之外完全来自实现的界面。

What's nice with that, is that you can @property in your class extension and hide your ivars completely from the .h, separating completely the interface from the implementation.

你也可以从.h中完全删除'{}',使其真正干净。

You can also remove completely the '{}' from the .h, making it really clean.

这篇关于对于obj-c中的属性,我们是否需要声明实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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