I've come across several examples which declares classes in the header differently like
NSStrin开发者_如何学编程g* mystring;
or
NSString *mystring;
What's the difference?
Those are three totally distinct lexical elements and the amount of whitespace in-between them is totally irrelevant. These are all equivalent in terms of what the compiler generates:
NSString*x;
NSString *x;
NSString* x;
NSString * x;
NSString * x;
NSString /* comment here */ * /* and another */ x;
I prefer the NSString *x
variation since the pointer specifier belongs to the variable, not the type. By that, I mean that both of these:
int *x, y;
int* x, y;
create an integer pointer called x
and an integer called y
, not two integer pointers.
There is no difference. It's a matter of style.
In Objective-C, you can pretty much think of the star as part of the 'type' of the variable.
However, the compiler interprets the star as "treat this variable as a pointer to the declared type" (in this case NSString). Where it gets interesting is defining multiple variables at once:
NSString *myString, *yourString;
You must use the star on each variable.
Is preference, and is useful if you declare multiple variables in the same line, viz
NSString* mystring1, mystring2; // Misleading, mystring2 is not a *
NSString *mystring1, mystring2; // Is more clear
no difference, just coding style preference.
Nothing, it isn't even important to have space between them. You can even write NSString*mystring
.
There is no differences in reality.
None whatsoever - it's a personal preference as to whether you think...
Here comes a variable that's of type NSString pointer (
NSString* mystring
)or
Here comes a variable of type NSString that's a pointer (
NSString *mystring
)
...is more legible. That said, as long as you're consistent it isn't something you should loose sleep over.
In C (and Objective-C, as a superset of C), placement of the *
is merely a matter of style.
I'd recommend checking out the relevant section from Google's style guide.
There's no difference. It's a matter of preference and style.
NSString
pointer (NSString* mystring)
NSString
that's a pointer (NSString *mystring)
Advantage of the first approach:
When coding to protocols, there's no issue with some variables having a star and some not. Example:
NSString* _myString
id<SomeProtocol> _collaborator
versus (more confusing):
NString *_myString
id<SomeProtocol> _collaborator
Drawback to this approach: (as pointed out)
//Only the first is a pointer.
NSString* _myString, _anotherString
Modern OO languages (like Java) tend to discourage multiple variables on one line: http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html#2991
精彩评论