I've a NSArray of MyObjects.
I want to duplicate the last object of my array. In other terms, I want to add a new object to the array that's exactly the same of the last one.
I tried with:
id object = [[self arrangedObjects] lastObject];
id newObject = [object copy];
But I've realized that I can't use copy method, because it is not implemented in NSObject.
Should I implement the copy method in MyObject class, returning a new instance of MyObject and change the code as follows:
MyObject object = [[self arrangedObjects] lastObject];
MyObject newObject = [object copy];
Or are there other solutoins ?
UPDATE From NSObject documentation
NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.
As far as I know, if you want to copy an object, implement the NSCopying protocol, which lets you use NSObject - (id)copy
method.
In the - (id)copyWithZone:(NSZone *)zone
method, allocate a new object using + (id)allocWithZone:(NSZone *)zone
then copy its members, update its states, and so on