Jan49
Jan49

Reputation: 1818

How to duplicate a custom object?

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?

Upvotes: 1

Views: 1433

Answers (2)

Sandy Rawat
Sandy Rawat

Reputation: 695

 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

Upvotes: 3

Kent
Kent

Reputation: 2960

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

This answer is a really good example

Upvotes: 0

Related Questions