开发者

Why put underscore "_" before variable names in Objective C [duplicate]

This question already has answers here开发者_StackOverflow中文版: Closed 10 years ago.

Possible Duplicate:

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

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

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


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.

Example:

@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

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, 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).

You access the properties as

myString = self.myIVar;

or, from another class:

theString = otherClass.myIVar;

and

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

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


Don't do it.

Single leading underscores are an Apple internal coding convention. They do it so that their ivar names won't collide with yours. If you want to use a prefix on your ivar names, use anything but a single underscore.


this is a naming convention normally used for c++ to define instance variable which are private

like in a class u may have

private:
int __x;

public:
int GetX()
{
  return this.__x;
}

this is a naming convention, i was forced to use in c++. However my teacher never told us the name of the naming convention. But i feel this is helpfull and readable specially when u are not using java naming conventions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜