I need to deep copy a custom object that has objects of its own. I've been reading around and am a bit confused as to how to inherit NSCopying and how to use NSCopyObject.
Two such methods are the copy and mutableCopy methods. These methods use something called the <NSCopying> Protocol. This protocol defines what must be implemented in an object in order for it to be copyable using the copy and mutableCopy methods.
Copy is useful when you do not want the value that you receive to get changed without you knowing. For example if you have a property that is an NSString and you rely on that string not changing once it is set then you need to use copy.
Copies the value of a named property to another property. This is useful when you need to plug in the value of another property in order to get a property name and then want to get the value of that property name.
As always with reference types, there are two notions of "copy". I'm sure you know them, but for completeness.
You want the latter. If this is one of your own objects, you need simply adopt the protocol NSCopying and implement -(id)copyWithZone:(NSZone *)zone. You're free to do whatever you want; though the idea is you make a real copy of yourself and return it. You call copyWithZone on all your fields, to make a deep copy. A simple example is
@interface YourClass : NSObject <NSCopying> { SomeOtherObject *obj; } // In the implementation -(id)copyWithZone:(NSZone *)zone { // We'll ignore the zone for now YourClass *another = [[YourClass alloc] init]; another.obj = [obj copyWithZone: zone]; return another; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With