Why do I have to write *myPointerVar only SOMETIMES in Objective-C?

后端 未结 3 854
北恋
北恋 2020-12-10 21:04

That\'s an issue I still don\'t understand.

Sometimes I have to write:

NSString* myVariable;
myVariable = @\"Hey!\";

Then, for exam

相关标签:
3条回答
  • 2020-12-10 21:25

    As you say, myVar is a pointer. As such, myVar.x is not correct: it would by a field of a pointer, which has no sense in C/Objective-C.

    If you want to access to the variable pointed to by a pointer, you have to add the asterisk: myVar is a pointer, *myVar is the variable pointed to by myVar.

    Moreover, in your case, you can use a special construct of C by writing myVar->x, which is strictly equivalent to (*myVar).x.

    All of this is standard C, not specific to Objective-C.

    About your first example, you don't have to put an asterisk because you change the value of the pointer, not the value of the variable: myVariable is a pointer to an object which at declaration time is assigned the nil value. The next instruction (myVariable = @"Hey!") is an assignment of pointer values: @"Hey!" is a pointer to a NSString object. The value of this pointer (not the value of the pointed constant) is assigned to myVariable, which then points to the object @"Hey!".

    Yes, this is diffucult to follow at first time...

    0 讨论(0)
  • 2020-12-10 21:31

    taken from the learning objective c link via the developers portal for iphone devs:

    Objective-C supports both strong and weak typing for variables containing objects. Strongly typed variables include the class name in the variable type declaration. Weakly typed variables use the type id for the object instead. Weakly typed variables are used frequently for things such as collection classes, where the exact type of the objects in a collection may be unknown. If you are used to using strongly typed languages, you might think that the use of weakly typed variables would cause problems, but they actually provide tremendous flexibility and allow for much greater dynamism in Objective-C programs.

    The following example shows strongly and weakly typed variable declarations:

    MyClass *myObject1; // Strong typing

    id myObject2; // Weak typing

    Notice the * in the first declaration. In Objective-C, object references are pointers. If this doesn’t make complete sense to you, don’t worry—you don’t have to be an expert with pointers to be able to start programming with Objective-C. You just have to remember to put the * in front of the variable names for strongly-typed object declarations. The id type implies a pointer.

    0 讨论(0)
  • 2020-12-10 21:42

    * is the dereference operator. All that *myVar means is "Get me the thing that the pointer myVar points to". You need this distinction because you need to tell the computer that you want to change the thing that myVar points to, not myVar itself.

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