That’s an issue I still don’t understand.
Sometimes I have to write:
NSString* myVariable; myVariable = @'Hey!';
Then, for example I define a Structure ‘DemoStruct’ and get an Variable that uses it. Lets say I have a Structure that has x and y vars from type double.
I want to pass this var to a method which then manipulates my var, and I want that this manipulation has effect on the context from which I passed the var to that method. So I need a pointer, right.
I pass it to the method like that:
[someObject someMethod:&myVarThatUsesTheStruct]
that method now looks like that:
- (void)someMethod:(DemoStruct*)myVar { (*myVar).x += 10; }
Before the call, the component x of the struct was lets say 1000. Now, 10 is added and it is 1010 after the method call.
But I really really hardly dont get it why I have to use the Asterisk * for myVar in the Method, since I say already in the Method Header that myVar is a POINTER to a DemoStruct. I just pass with &myVarThatUsesTheStruct the memory address.
Can someone explain why this is like it is?
As you say,
myVaris 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:
myVaris a pointer,*myVaris the variable pointed to bymyVar.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:
myVariableis a pointer to an object which at declaration time is assigned thenilvalue. The next instruction (myVariable = @'Hey!') is an assignment of pointer values:@'Hey!'is a pointer to aNSStringobject. The value of this pointer (not the value of the pointed constant) is assigned tomyVariable, which then points to the object@'Hey!'.Yes, this is diffucult to follow at first time…