相关疑难解决方法(0)

在cocoa objective-c类中变量前面的下划线如何工作?

我在一些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'的东西不是结构或联合

variables syntax cocoa cocoa-touch objective-c

156
推荐指数
4
解决办法
5万
查看次数

在Objective C中使用下划线前缀属性名称

我以前在变量名称中避免使用下划线,这可能是我大学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的偏好.我已经学会了停止担忧并且喜欢下划线.

iphone coding-style objective-c

55
推荐指数
5
解决办法
2万
查看次数

属性名称上的下划线前缀?

可能重复:
cocoa objective-c类中变量前面的下划线如何工作?

任何人都可以向我指出使用下划线的解释,我一直认为它们用于突出显示您正在访问iVar [_window release];而不是通过setter/getter方法访问iVar,[[self window] release];或者[self.window release];我只是想验证我的理解是正确.

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UILabel *markerLabel;

@synthesize window = _window;
@synthesize markerLabel = _markerLabel;
Run Code Online (Sandbox Code Playgroud)

cocoa-touch objective-c

11
推荐指数
2
解决办法
7140
查看次数