objective-c - 为什么我总是看到双重属性(property)声明?

标签 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.

引用: https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1

关于objective-c - 为什么我总是看到双重属性(property)声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202709/

上一篇:iphone - locationManager didFailWithError 重复调用

下一篇:objective-c - 使 UITableView 的第一个单元格与其他每个单元格不同

相关文章:

ios - 应用反馈表

MeteorJS 的 iOS 9 Beta 2 网络问题

ios - 在 Swift 中使用扩展协议(protocol)的类函数?

iphone - View Controller 的全局实例是否应该由应用程序委托(delegate)拥有

objective-c - 核心动画 anchor 被忽略?

objective-c - 有没有办法标记一个不返回的 Objective-C 方法?

ios - drawAtPoint 不会在 View 中渲染文本

objective-c - UILabel 动态内容自动调整大小问题

iphone - 根据 UITextView 框架大小调整文本

iphone - 如何通过iPhone中的侧面音量控制按钮使用系统声音服务控制文件播放的音量