Question

For trying out some pointer stuff, I made an instance variable in an existing project. It's just declared like this:

@interface PointerFun : NSObject {
    NSString* test;
}

I have no @property compiler directive, no @synthesize, so no getter and no setter. Just for testing.

Then I have a method, where I try around some things with pointers and this instance variable. What I actually wanted to check out is what would happen when I assign that instance variable an NSString object (or whatever object), and after assigning the object, assign another object to that pointer which I assigned to the instance var. I thought that it would change the object in the instance var as weell.

So here's my code:

NSString *str1 = [NSString stringWithCString:"one"];
NSString *str2 = [NSString stringWithCString:"two"];

test = str2; // assign directly to instance variable (bad thing, just for testing!)
str2 = str1; // now lets be really mean and change the object from that pointer!!

NSLog(@"test: %x, %@", test, test); // test: 52cb10, two
NSLog(@"str1: %x, %@", str1, str1); // str1: 52ca60, one 
NSLog(@"str2: %x, %@", str2, str2); // str2: 52ca60, one

Like you see, the instance variable keeps pointing to the NSString object that was early behind str2. So when I assigned str1 to str2, I assigned the value of str1 to str2, which is a memory address. So I made both pointers have the same value, right?

But when I assigned the value of str2 to test, test took over the value from str2, which was -at that time- the memory address for the "two" object. So even if I change after that assignment the value of the pointer str2, it will not affect the instance variable's value. And because that is an pointer to an NSString object, it just behaves the same as if it was str1 or str2. There is no difference just because it's an instance var. It's just an variable, or better: it's just an pointer. Did I get that right? phew ;) ...hope so!

Was it helpful?

Solution

The three variables are actually pointers (test, str1 and str2), and you have 2 objects created: "one" and "two".

When you do:

test = str2;

you are making test point to the object "two", and when you do:

str2 = str1;

you are making str2 point to the object "one", which does not affect test at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top