我在一些iPhone示例中看到,属性在变量前面使用了下划线_.有谁知道这意味着什么?或者它是如何工作的?
我正在使用的接口文件如下所示:
@interface MissionCell : UITableViewCell {
Mission *_mission;
UILabel *_missionName;
}
@property (nonatomic, retain) UILabel *missionName;
- (Mission *)mission;
Run Code Online (Sandbox Code Playgroud)
我不确定上面做了什么,但是当我尝试设置任务名称时:
aMission.missionName = missionName;
Run Code Online (Sandbox Code Playgroud)
我收到错误:
请求成员'missionName'的东西不是结构或联合
我以前在变量名称中避免使用下划线,这可能是我大学Java时代的延续.因此,当我在Objective C中定义一个属性时,这就是我自然而然的事情.
// In the header
@interface Whatever
{
NSString *myStringProperty
}
@property (nonatomic, copy) NSString *myStringProperty;
// In the implementation
@synthesize myStringProperty;
Run Code Online (Sandbox Code Playgroud)
但在几乎所有的例子中都是如此
// In the header
@interface Whatever
{
NSString *_myStringProperty
}
@property (nonatomic, copy) NSString *myStringProperty;
// In the implementation
@synthesize myStringProperty = _myStringProperty;
Run Code Online (Sandbox Code Playgroud)
我应该克服对下划线的厌恶,因为这是应该做的一种方式,这种风格是否是一个很好的理由?
更新:现在使用自动属性合成你可以省略@synthesize,结果和你使用的一样
@synthesize myStringProperty = _myStringProperty;
Run Code Online (Sandbox Code Playgroud)
这清楚地表明了Apple的偏好.我已经学会了停止担忧并且喜欢下划线.
可能重复:
在Objective C中使用下划线前缀属性名称
我刚刚开始iphone App开发并注意到当你生成一个新项目时,可以在AppDelegate.m中看到以下代码
@synthesize window = _window;
@synthesize viewController = _viewController;
Run Code Online (Sandbox Code Playgroud)
它说,在AppDelegate.h文件中
@property (strong, nonatomic) UIWindow window;
@property (strong, nonatomic) ViewController controller;
Run Code Online (Sandbox Code Playgroud)
我想知道究竟是什么意思,特别是合成部分.它是否实例化了一个本地私有变量?如果是这样,这与说@synthesize viewController有什么不同;
谢谢
objective-c ×3
iphone ×2
cocoa ×1
cocoa-touch ×1
coding-style ×1
syntax ×1
variables ×1
xcode ×1