可能是重复问题:
在cocoa的objective-c类中,变量前面的下划线是如何工作的?
我在Apple公司的UIPickerView.h文件中看到过这个:
id<UIPickerViewDataSource> _dataSource;
为什么这里有下划线?它有特殊的含义吗?我需要知道的约定吗?
可能是重复问题:
在cocoa的objective-c类中,变量前面的下划线是如何工作的?
我在Apple公司的UIPickerView.h文件中看到过这个:
id<UIPickerViewDataSource> _dataSource;
为什么这里有下划线?它有特殊的含义吗?我需要知道的约定吗?
@synthesize var = _var;
这样的结构也(温和地)指导您有建设性地使用访问器和点符号语法。 - Joe D'Andrea你所看到的是使用下划线来区分实例变量和属性。因此,一个类声明可能会是这样的:
@interface Foo {
NSString* _label;
....
}
@property (nonatomic, retain) NSString* label; // notice: no underline
然后在实现文件中,您将拥有:
@synthesize label=_label; // the property is matched with the ivar
现在,在实现内部,如果你想直接访问实例变量,可以使用_label
,但是要通过属性访问器方法(其会处理保留/释放和一堆其他簿记任务)访问它,你应该使用self.label
。从外部来看,你总是要通过{object}.label
属性进行访问。NSString* label;
@property (nonatomic, retain) NSString* label;
...
@synthesize label;
它的效果是相同的,但会使读取代码并尝试跟踪
如前所述,_someVar 用于表示变量是私有的。这只是一种惯例问题,实际上并不重要。
另一个用途,在C语言中,_function() 表示函数不具有平台可移植性,而__function() 则表示函数没有编译器可移植性。因此,在标准C库中,有时会看到名称前面带有 _ 或 __ 的变量,这就是这些函数所代表的意思。
有时它用于表示私有变量。更普遍地,它只是意味着“这个变量在某种程度上不同”。
这是不是可能......(唤起记忆)...
我模糊地记得读过一份ADC文档,解释了苹果保留使用下划线前缀成员变量的权利?并且第三方开发者被劝阻使用此约定以避免冲突?
|K<
我使用下划线来表示变量是成员变量,类似于匈牙利命名法中的'm'前缀(我非常厌恶这种命名法,但那是另一个故事)。当然,现在有彩色编码编辑器,但我的观点是,在你输入变量之前,这个前缀让你想到变量是成员/实例,而不仅仅是在后来被编辑器着色时。
我选择使用下划线作为实例变量的命名方式,因为我经常遇到以下情况:
@interface MyClass:NSObject
{
NSUInteger count;
}
@property(nonatomic) NSUInteger count;
-(id) initWithCount(NSUInteger) count;
@end
(...)
@implementation MyClass
@synthesize count;
-(id) initWithCount(NSUInteger) count
{
if((self = [super init])){
self.count = count; // Parameter name collides with ivar name!
}
return self;
}
@end
所以我这样做:
@interface MyClass:NSObject
{
NSUInteger _count;
}
@property(nonatomic) NSUInteger count;
-(id) initWithCount(NSUInteger) count;
@end
(...)
@implementation MyClass
@synthesize count = _count;
-(id) initWithCount(NSUInteger) count
{
if((self = [super init])){
_count = count; // No name collision
}
return self;
}
@end
当然,我也可以将参数名称更改为“newCount”或“aCount”(我讨厌那个)。我认为这是一个品味问题。