The asterisk in Objective-C object instance declarations: by the Object or by the instance? [duplicate]
Possible Duplicate:
What's your preferred pointer declaration style, and why? In C, why is the asterisk before the开发者_开发问答 variable name, rather than after the type? What makes more sense - char* string or char *string?
When declaring a new instance of an object in Objective-C, does it make any difference where you put the asterisk?
Is this just a matter of personal preference?
NSString* string = @"";
vs.
NSString *string = @"";
It doesn't make a difference, but there are good reasons to put it in each place:
It makes sense to put it near the class, because that makes it feel like a type:
NSString*
, a pointer to a string. Sensible.It makes sense to put it near the variable, because that's what's actually happening:
*
is dereference. When you dereference your pointerstring
, you get anNSString
.*string
is anNSString
. Sensible.
You may want to go with the latter because that's the way the compiler is thinking, so: NSString* oneString, anotherString
will not work, whereas NSString *oneString, *anotherString
is correct.
It's simply a matter of preference. Putting the * next to the type emphasizes that it's part of the type, i.e. "pointer to an NSString". However, this is usually frowned upon, because it ignores the fact that the * associates with the nearest variable name, not the type name. For instance, the following doesn't work:
NSString* a = @"string1", b = @"string2
This is because a is a pointer, but b is not.
Putting the * next to the variable name is, in my opinion, more of a C/C++ convention, because it emphasizes that the * and the variable name together act kind of like a variable.
Personally, I put a space on both sides of the *.
Another question that asked the same thing is here:
Declaring pointers; asterisk on the left or right of the space between the type and name?
It doesnt make the difference wher you put that pointer symbol. If you declare multiple objects in single line, you do it like NSString *str1, *str2. So its more appropriate to put that asterisk close to object. I prefer it close to object instance.
精彩评论