Copy of an NSObject subclass

NSObject class does not support copying so it has to be implemented in its subclass. If a class MyClass is an NSObject subclass, it needs to implement NSCopying protocol and its copyWithZone method in order for its instance to be copied.

The MyClass variables are defined below…

@interface MyClass : NSObject < NSCopying > 
{
	NSString *string;
	NSMutableArray *mutableArray;
	NSDate *date;
}

To make a copy, the copyWithZone method is used. A new object is created and its variables are copied.

- (id)copyWithZone:(NSZone *)zone
{
	MyClass *myClassInstanceCopy = [[MyClass allocWithZone: zone] init];

	myClassInstanceCopy.string = [string copy];
	myClassInstanceCopy.mutableArray = [mutableArray mutableCopy];
	myClassInstanceCopy.date = [date copy];

	return myClassInstanceCopy;
}

It is important to copy member variables instead of just assigning them because we want two objects with the same values – copies!