boyfarrell.com

26 April 2007

Implementing Object Copy

Found a handy little reference today (click link below) about conforming to the NSCoding Protocol:

Apple Conceptual Cocoa Documentation

If you want your objects to be become part of NSDictionary classes then you will need to add the -copyWithZone: method in your class. If your objects only contain primative types such as double, int, BOOL etc. then the copying is fairly straight forward. Override -copyWithZone: method in which you create a new object inside assign the current variables and return it.

However, it is more common to have objects in ones classes in this situation there are different ‘levels’ of copying; ‘shallow’ and ‘deep’. Both require that you return an new object. The difference arrives from how the instance variables are linked to the copy.

In a shallow copy one simply copies the pointers to the original object. This has the consequence of making the data shared.

A deep refers to the process of giving the copy allocating new copies for all (even those inherited) instance variables the object has. This technique is more a ‘snap-shot’ of the state of the object at that particular point in time.

Example Class

If I have an object representing a point in 3D space with primative data types,


@interface DJFPoint : NSObject {
unsigned int x,y,z;
}
- (unsigned int) x;
- (unsigned int) y;
- (unsigned int) z;

- (void) setX: (unsigned int) newX;
- (void) setY: (unsigned int) newY;
- (void) setZ: (unsigned int) newZ;

the most sensible copy is by value.

Override -copyWithZone:

- (id) copyWithZone:(NSZone*) zone{
DJFPoint *copy = [[DJFPoint alloc] init];
[copy setX:[self x]];
[copy setY:[self y]];
[copy setZ:[self z]];

return copy;
}

See the apple article for lots of useful examples on this.

No Comments currently posted.

Post a comment on this entry: