I recently picked up the BigNerdRanch book on Cocoa for Mac OSX and am looking for a good explanation around the use of asterisks * and underscores _ that seem to be inconsistently used throughout the language. Some examples:
These appear to be functionally equivalent:
NSString* myString;
NSString *myString;
Sometimes new variables get an underscore, while others dont:
NSString _myString;
NSString myString;
And sometimes it gets all crazy:
NSString *myString;
NSString *_myString;
I’ve also seen variations with asterisks in methods:
- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender
willSpeakWord:(NSRange)characterRange
ofString:(NSString *)string;
So what is the functional use of the asterisk or the underscore, when should you use (or not use) either, and when should they be used in combination?
The
*indicate a pointer, which all Objective-C objects are. (You pass around pointers to these objects in memory). At a basic level these are normal C pointers. If I remember correctly You could access some data in an Objective-C object by goingobject->data, just like you do with pointers to C structs.The
_is a Cocoa (and some other languages) convention, meaning “a piece of data that should be considered private to this object”.Objective-C has a
@privatedeclaration, but it’s also a relatively new addition to the language – if your code is more than 2 or 3 years old (or targeting much older versions of OS X) it might not use@privateBecause of this initial lacking of language infrastructure, the
_is (often) used by the Cocoa community to mark “Hey, you probably shouldn’t set or read this directly, please”.So:
*to follow the class name (likeNSString), because they are always pointers. I’m confused about yourNSString somestringline in your code – either that’ll generate a complier warning or will crash when you try to use it_indicates private data. You would do something likeNSString* _namein a@interfacesection of your Objective-C class. You would use_nameby itself if you were calling or operating on that data in a method in your class.So say you created a Student class:
Here we declare a class with a “private” data member:
_name. OurStudentclass needs to return this capitalized for some reason, so we created a method to do that, where we use_nameand call theuppercasemethod on it.We needed to refer to the type (or class name) or _name a few times here: once, to declare the variable. For
name_as_capswe needed to say:this method returns a pointer to an NSString object, thus we usedNSString *.