Question

In my child view controller, I have a property defined as:

@property (nonatomic, copy) NSString *name;

In view controller A, the Parent, I have the following:

NSString *temp = currency.name; //This is because currency is a Core Data Managed Object.
                                //I wanted to make sure it wasn't a confounding factor.

childViewController.name = temp;

if(childViewController.name == temp)
  NSLog(@"I am surprised");

The problem is that if statement finds equivalency and the "I am surprised" is printed. I thought that == should be checking if they're the same object, and that the use of copy in the property declaration should ensure the setter is making a copy. I checked in the debugger and they are both pointing to the same string. (Which I believe is immutable, which may be why this is happening?)

The same thing happens even if I write childViewController.name = [temp copy];, which I find shocking!

Can anyone explain what is going on here?

Edit: I removed a bit here on worrying about a circular reference which I realized wasn't a concern.

Was it helpful?

Solution

This is an optimization.

For immutable objects, it's superfluous to create an actual copy, so - copy is often implemented as a simple retain, i. e.

- (id)copy
{
    [self retain];
    return self;
}

Try assigning a mutable object (e. g. NSMutableString) to the property, and you will get the "expected" behavior.

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