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,
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 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:
myVariable
is a pointer to an object which at declaration time is assigned thenil
value. The next instruction (myVariable = @"Hey!"
) is an assignment of pointer values:@"Hey!"
is a pointer to aNSString
object. 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...
Javier : 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!mouviciel : Yes, when I wrote this last sentence I thought something like: "for a tutorial on pointers, learn an assembly language" -
* 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 comments:
Post a Comment