Copy an object?

ksignorini

Registered
Is there a simple way to copy an object in Objective C or do I need to create a new object then copy all the instance variables from the original to the new one by myself?

Thanks,
Kent!
 
If it's a Cocoa object, you can make a copy with [myObject copy]. If it's your own custom object, you have to implement its method -(id) copyWithZone:(NSZone *)zone before you can use [myObject copy]. The default behavior of -copy is to call -copyWithZone: so you don't need to override -copy.

Code:
- (id) copyWithZone:(NSZone *)zone
{
    MyObject * aCopy = [super copyWithZone:zone];
    [aCopy setFoo:[self foo]];
    [aCopy setBar:[self bar]];
    return aCopy;
}

If you're curious about zones, these allow similar objects to be allocated near each other in memory, rather than all over the address space. This way, a cache hit may cause multiple objects to be put into the cache for faster access. NSMenu and NSMenuItem are examples of objects which normally have their own zone. Generally, you don't need to worry about using zones yourself unless you have definite proof that they'll boost speed.
 
Back
Top