用下划线作为前缀命名实例变量在Cocoa(Objective-C)中是否有任何副作用? [英] Does naming an instance variable with underscore as a prefix have any side effects in Cocoa (Objective-C)?

查看:174
本文介绍了用下划线作为前缀命名实例变量在Cocoa(Objective-C)中是否有任何副作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?

我发现在Apple框架的头文件中,类接口内带有前缀underscope的Apple名称实例变量. 类似于下面的_delegate实例:

I found that in Apple's frameworks' header files , Apple name instance variable with prefix underscope inside a class interface. like the _delegate instance below:

@interface ClassName : NSObject {
    id _delegate;
}
@end

但是,如果在定义自己的实例变量时遵循此命名约定,会不会有副作用?我一直在寻找这个问题的答案很长一段时间.

But is there any side effects if we follow this naming convention when defining our own instance variable? I've been searching the answer for this question for quite a long time.

在Apple的代码指南中,Apple只是说他们保留方法名称以下划线开头,他们没有提到对实例变量的命名问题的任何限制.

In apple's Code Guideline, apple just said they reserve the methods name begin with underscore, they haven't mention any restriction about instance variable's naming problem.

我的同事说,如果您定义的实例变量以下划线开头,那么如果您选择的名称存在于框架的私有头文件中,则下划线可能会与框架发生冲突.这是否可能,或者这是否成为我们不应该使用下划线开头的名称(因为苹果可能已经使用过该名称)的原因?

My colleague said if you define instance variable begin with underscore might get collide with the framework if the name you pick exist in the framework's private header file. Is this possible or does this become a reason that we shouldn't use the name begin with underscore because apple might already used it?

推荐答案

没有副作用.但是使用下划线会使访问私有ivars和函数参数名称时的代码读取变得容易得多.

There is no side-effect. But using an underscore makes reading code a lot easier when accessing private ivars and function parameter names.

例如,假设您的头文件中有NSString *_name;. 然后在您的代码中将如下所示:

For example let say you have NSString *_name; in your header file. Then in your code would read like so:

- (void)doSomethingWithName:(NSString *)name {
    // the underscore makes reading code easier
    _name = [name retain];
    name = [_name retain];  // you know right away that this is wrong
}

我个人遵循 Google Objective-C样式指南,并使用跟踪下划线.所以我的值是:NSString *name_;

I personally follow Google Objective-C Style Guide and use a trailing underscore. So my ivars would be: NSString *name_;

这篇关于用下划线作为前缀命名实例变量在Cocoa(Objective-C)中是否有任何副作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆