views:

291

answers:

2

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?

+3  A: 

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...

mouviciel
i have to disagree with your last sentence "this is diffucult to follow at first time". it's only difficult if you learn first high level languages and go down. going upwards from low-level makes these the easiest things in programming!
Javier
Yes, when I wrote this last sentence I thought something like: "for a tutorial on pointers, learn an assembly language"
mouviciel
+1  A: 

* 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.

Jason Punyon