开发者

Questions about duplicating last object of a NSArray

开发者 https://www.devze.com 2023-04-08 14:45 出处:网络
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'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 开发者_Go百科the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号