<分区>
标签 objective-c ios
<分区>
Possible Duplicate:
When do I need to have both iVar and a property?
我不断在 Objective-C 代码中看到以下内容。
@interface Contact : RKObject {
NSNumber* _identifier;
NSString* _name;
NSString* _company;
}
@property (nonatomic, retain) NSNumber* identifier;
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* company;
为什么还需要带有接口(interface)的 block 内部的位?那是不是使用@synthesize?
最佳答案
@interface
中的 block 是你的类的 ivars
,而它下面的 3 个元素是 properties
,即访问器(getters 和 setters)为你的 ivars。
You typically access an object’s properties (in the sense of its attributes and relationships) through a pair of accessor (getter/setter) methods. By using accessor methods, you adhere to the principle of encapsulation. You can exercise tight control of the behavior of the getter/setter pair and the underlying state management while clients of the API remain insulated from the implementation changes.
Although using accessor methods therefore has significant advantages, writing accessor methods is a tedious process. Moreover, aspects of the property that may be important to consumers of the API are left obscured—such as whether the accessor methods are thread-safe or whether new values are copied when set.
Declared properties address these issues by providing the following features:
- The property declaration provides a clear, explicit specification of how the accessor methods behave.
- The compiler can synthesize accessor methods for you, according to the specification you provide in the declaration.
- Properties are represented syntactically as identifiers and are scoped, so the compiler can detect use of undeclared properties.
关于objective-c - 为什么我总是看到双重属性(property)声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202709/