1

I need to duplicate a custom object. Is is possible without copying each and every field manually?

 var test1  = CustomerInfo()
 var test2 = CustomerInfo()
 test1 = test2
 test1.customername = "First"
 test2.customername = "Second"

 print(test1.customername) /* Getting "Second" , actually i want to get "First" */

Please suggest me any possible solution?

Jan
  • 1,744
  • 3
  • 23
  • 38

2 Answers2

3
 func copy(with zone: NSZone? = nil) -> Any {
        let copy = CustomerInfo(myIvar1: Type, myIvar2: type)//constructor or your class
        return copy
    }
 var test1  = CustomerInfo()
 var test2 = test1.copy as! CustomerInfo

hello Jan,

  1. You need to confirm to the protocol NSCopying and implement the above copyWithZone: method .

  2. Inside copyWithZone method just create the object using your constructor method and return that object.

  3. Whenever you want to copy just call copy on your exciting object. for complete reference follow this on apple official https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCopying.html

And if only Copy is main concern to your object just use Structure instead of class as they are value type not reference type. Changing your class to structure will make your type a value type but with lot of object oriented limitations. Thanks

Sandy Rawat
  • 685
  • 7
  • 12
0

Because class is reference type, you can use struct (value type) to do that

This answer is a really good example

Kent
  • 2,952
  • 2
  • 25
  • 42