user1628311
user1628311

Reputation: 186

In a method does the pointer or actually object get passed as a parameter?

I have been messing around with a bit of code to try and get my head around pointers and memory management in objective-c. However, what I can't seem to understand is that using this code:

hello *myHello = [[hello alloc] init];

NSString *string = @"Hello";

myHello.property = string;

does the NSString instance (@"Hello") get passed as a parameter to the setter method or does the pointer get sent. For example if I changed "string" to point to a different object and then got the variable would it still be "Hello" or change to the new object that "string" pointed to? Thanks in advance!

Upvotes: 0

Views: 98

Answers (2)

Jim Rhodes
Jim Rhodes

Reputation: 5095

When you do:

myHello.property = string;

If property is defined without copy, it is set to point to the same place that string points to.

If property is defined with copy, it is set to point to a new copy of the original string.

In either case, if you then change string to point to a different string (e.g. @"Goodbye"), property will still point to @"Hello".

Upvotes: 0

Josiah
Josiah

Reputation: 4793

Jim had a good answer, but I want to add a visual one as it might help people.

Say *string = @"test"

string is pointing to a memory location that stores @"test"

Esentially, it looks like this:

      @"test"
        ^
string /

When you do:

myHello.property = string;

You are just setting property to the same place string was, like this;

     @"test"
        ^
string /  \ property

Then, if you later change string to say @"hello" You create another location in memory, and keep the other. Now it is like this.

      @"hello"  @"test"
        ^         ^
string /           \ property 

The only way property could be tampered with is if you messed with the pointer. Since that will probably never happen, you don't need to worry about it.

Some newbies think that this will cause memory problems, but it won't. ARC can tell when you are done with property and it will remove the memory itself.

Hope that helps!

Upvotes: 1

Related Questions