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 going object->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 @private
declaration, 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 @private
Because 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:
- When dealing with Objective-C classes you always need the
*
to follow the class name (like NSString
), because they are always pointers. I'm confused about your NSString somestring
line in your code - either that'll generate a complier warning or will crash when you try to use it
- The
_
indicates private data. You would do something like NSString* _name
in a @interface
section of your Objective-C class. You would use _name
by itself if you were calling or operating on that data in a method in your class.
So say you created a Student class:
// Student.h
@interface Student : NSObject {
NSString* _name;
}
- (NSString*) name_as_caps;
@end
// Student.m
@implementation Student
- (NSString*) name_as_caps {
return [_name uppercase];
}
Here we declare a class with a "private" data member: _name
. Our Student
class needs to return this capitalized for some reason, so we created a method to do that, where we use _name
and call the uppercase
method 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_caps
we needed to say: this method returns a pointer to an NSString object
, thus we used NSString *
.