Cocoa Objective-c 类中变量前面的下划线如何工作? [英] How does an underscore in front of a variable in a cocoa objective-c class work?
问题描述
我在一些 iPhone 示例中看到,属性在变量前使用了下划线 _.有谁知道这是什么意思?或者它是如何工作的?
I've seen in a few iPhone examples that attributes have used an underscore _ in front of the variable. Does anyone know what this means? Or how it works?
我使用的接口文件如下所示:
An interface file I'm using looks like:
@interface MissionCell : UITableViewCell {
Mission *_mission;
UILabel *_missionName;
}
@property (nonatomic, retain) UILabel *missionName;
- (Mission *)mission;
我不确定上面具体做了什么,但是当我尝试将任务名称设置为:
I'm not sure exactly what the above does but when I try to set the mission name like:
aMission.missionName = missionName;
我收到错误:
在非结构或联合体中请求成员missionName"
request for member 'missionName' in something not a structure or union
推荐答案
如果你为你的 ivars 使用下划线前缀(这只不过是一个常见的约定,但很有用),那么你需要做 1 件额外的事情所以自动生成的访问器(用于属性)知道要使用哪个 ivar.具体来说,在您的实现文件中,您的 synthesize
应如下所示:
If you use the underscore prefix for your ivars (which is nothing more than a common convention, but a useful one), then you need to do 1 extra thing so the auto-generated accessor (for the property) knows which ivar to use. Specifically, in your implementation file, your synthesize
should look like this:
@synthesize missionName = _missionName;
更一般地说,这是:
@synthesize propertyName = _ivarName;
这篇关于Cocoa Objective-c 类中变量前面的下划线如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!