MatterGoal
MatterGoal

Reputation: 16430

Copying some data of an NSManagedObject to another

I have an NSManagedObject subclass (let's call it) Car with 2 properties of type NSNumber: speed and fuel.

If I have an instance of the class Car and I copy some values to a new instance, are these values connected or are just copied like using the method copy?

Here the code with my doubt:

// The object ferrari was previously obtained from fetch request

Car *lotus = [NSEntityDescription insertNewObjectForEntityForName:@"Repetition" 
                                           inManagedObjectContext:self.managedObjectContext];

// solution 1
lotus.speed = ferrari.speed;
lotus.fuel = ferrari.fuel; 

// solution 2 
lotus.speed = [ferrari.speed copy];
lotus.fuel = [ferrari.fuel copy]; 

Giving that I want to be sure that the two object are independent, so changing properties or lotus doesn't have to change properties of ferrari can I just use the solution 1?

Upvotes: 0

Views: 35

Answers (1)

Martin R
Martin R

Reputation: 539795

NSNumber objects are immutable. If you assign

lotus.speed = ferrari.speed;

then both attributes point to the same NSNumber object, but you cannot change that object. You can only assign a new object:

ferrari.speed = @(454);

but that will not change the value of lotus.speed. So you don't need to copy the object. The same is true for NSString attributes.

Upvotes: 2

Related Questions