为什么要在下划线"_"在目标C中的变量名之前 [英] Why put underscore "_" before variable names in Objective C

查看:97
本文介绍了为什么要在下划线"_"在目标C中的变量名之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在目标C中,我看到很多代码在变量名(例如_someVariable)之前带有下划线.

In objective C I am seeing lots of code with a underscore before variable names e.g _someVariable

那是为什么?还有如何编写访问器,即此类变量的get和set方法.

why is that? also how to you write accessors i.e get and set method for such a variable.

推荐答案

下划线通常用于表明变量是 instance变量.确实没有必要,因为 ivars 可以与它们的属性和访问者具有相同的名称.

The underscores are often used to show that the variables are instance variables. It is not really necessary, as ivars can have the same name as their properties and their accessors.

示例:

@interface MyClass : NSObject {
    NSString *_myIVar;                  // can be omitted, see rest of text
}
// accessors, first one is getter, second one is setter
- (NSString *) myIVar;                  // can be omitted, see rest of text
- (void) setMyIVar: (NSString *) value; // can be omitted, see rest of text

// other methods

@property (nonatomic, copy) NSString *myIVar;

@end

现在,您可以让编译器执行此操作,而不是自己声明和编码访问器myIVarsetMyIVar:.在较新的版本中,您甚至不必在接口中声明myIVar.您只需声明该属性,然后让编译器为您合成其余的属性.在.m文件中,您可以执行以下操作:

Now, instead of declaring and coding the accessors myIVar and setMyIVar: yourself, you can let the compiler do that. In newer versions, you don't even have to declare myIVar in the interface. You just declare the property and let the compiler synthesize the rest for you. In the .m file, you do:

@implementation MyClass
@synthesize myIVar; // generates methods myIVar and setMyIVar: for you, 
                    // with proper code.
                    // also generates the instance variable myIVar

// etc...

@end

请确保最终确定字符串:

Be sure to finalize the string:

- (void) dealloc {
    [myIVar release]; 
    [super dealloc];
}

FWIW,如果您想要做的事情比getter或setter的默认实现要多,您仍然可以自己编写一个或两个代码,但是随后您还必须注意内存管理.在那种情况下,编译器将不再生成该特定的访问器(但是,如果仅手动完成一个,则仍将生成另一个访问器).

FWIW, if you want to do more than the default implementation of the getter or setter do, you can still code one or both of them yourself, but then you'll have to take care of memory management too. In that case, the compiler will not generate that particular accessor anymore (but if only one is done manually, the other will still be generated).

您以以下方式访问属性

myString = self.myIVar;

或者,来自另一个班级:

or, from another class:

theString = otherClass.myIVar;

otherClass.myIVar = @"Hello, world!";

在MyClass中,如果省略self.,则会得到裸露的 ivar .通常只应在初始化程序和dealloc中使用.

In MyClass, if you omit self., you get the bare ivar. This should generally only be used in the initializers and in dealloc.

这篇关于为什么要在下划线"_"在目标C中的变量名之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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