Pergunta

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.

Foi útil?

Solução

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

Outras dicas

If your objects are NSObject, you can make a new NSObject category that implements the NSCopying Protocol. Be sure to iterate through all keys and copy their value to your new object. For deep copying you should also call 'copy' on each of its value objects.

If your object is custom, implement the protocol in it's class.

If you have mixed objects in the array, all of them must implement NSCopying protocol therefor you can use id<NSCopying> when you declare them to avoid a compile time warning/error.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top