How to make a copy of a custom object
-
28-09-2019 - |
Question
I made a custom object that inherits from NSObject. Let's say I have an array of these objects. Then I want to make another object, that is a copy of one of the objects in the array. I do not want to simply point to an existing object in the array I want a copy. Is there an easy way to do this?
Solution
Implement the NSCopying
protocol on the object, and use it as follows:
MyFoo * theCopy = [[myArray objectAtIndex:0] copy];
Note that theCopy
is a retained object at this point, and should be released when you are done with it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow