Placement of the asterisk in Objective-C

前端 未结 14 962
鱼传尺愫
鱼传尺愫 2020-11-27 13:34

I have just begun learning Objective-C, coming from a VB .Net and C# .Net background. I understand pointer usage, but in Objective-C examples I see the asterisk placed in s

相关标签:
14条回答
  • 2020-11-27 14:26

    No difference, whitespace placement is irrelevant.

    0 讨论(0)
  • 2020-11-27 14:28

    it doesn't matter where you put your asterisk, all statements create pointers of type NSString.

    when using multiple variable names in one line you have to write the asterisk for each variable though.

    NSString * nsstring, * nsstring2;
    
    0 讨论(0)
  • 2020-11-27 14:30

    There is no difference — it's a matter of style. They all declare a variable called string that's a pointer to an NSString. The parentheses are necessary in some contexts (particularly method declarations) in order to clarify that it's a type declaration.

    0 讨论(0)
  • 2020-11-27 14:31

    the * works the same way as it does in standard C.

    this is a nice primer on putting the * in different places and what it does: http://boredzo.org/pointers/

    0 讨论(0)
  • 2020-11-27 14:32
    1.  NSString *string;
    2.  NSString * string;
    3.  (NSString *) string;
    4.  NSString* string;
    

    1,2 and 4 are equivalent. The C language (and the Objective-C superset of C) specify a syntax that is insensitive to white space. So you can freely add spaces where you choose as a matter of style. All relevant syntax is delimited by non-whitespace characters (e.g. {, }, ;, etc.) [1].

    3 is either a type cast (telling the C compiler to use the NSString* type regardless of the declared type of string. In Objective-C, type casting of object instances is rarely necessary. You can use the id type for variables that can reference instances of any object type.

    In method declarations, syntax 3 (sometimes without the ending semicolon) is used to declare the type of method parameters. An Objective-C method may look like this:

    - (void)myMethodThatTakesAString:(NSString*)string;
    

    In this declaration, the type of the argument named string is type NSString* (the leading - indicates an instance method as oppose to a class method). A method declaration with more than one parameter might look like this:

    - (void)myMethodTakingAString:(NSString*)string andAnInteger:(NSInteger)intParam;
    

    [1] This is compared to languages like Python which use whitespace as a block delimeter.

    0 讨论(0)
  • 2020-11-27 14:34

    There is absolutely no difference. NSString* mystring and NSString *myString are identical.

    0 讨论(0)
提交回复
热议问题