简体   繁体   中英

Make a copy of object with same address in swift

var empObj : EmployeeModel!
var tempObj : EmployeeModel!

tempObj = empObj.copy() as! EmployeeModel

whenevr I am copy the empObj to tempObj it's memory address is changed.I want to prevent this any idea?

when you copy its actually making a new reference. instead of copying just assign the value . then both will share the same reference

var empObj : EmployeeModel!
var tempObj = empObj

When you want the same address for different values

USE =

for eg.

var ogArray : NSMutableArray() var tempArray = ogArray

If you are using objects two variables can point at the same object so that changing one changes them both, whereas if you tried that with structs you'd find that Swift creates a full copy so that changing the copy does not affect the original. If you want to modify copies of a class object so that modifying one object doesn't have an effect on anything else, you can use NSCopying.

  • Make your class conform to NSCopying. This isn't strictly required
  • Implement the method copy(with:), where the actual copying happens.
  • Call copy() on your object.

Example Code for NSCopying

 class Person: NSObject, NSCopying {
    var firstName: String
    var lastName: String
    var age: Int

    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }

    func copy(with zone: NSZone? = nil) -> Any {
        let copy = Person(firstName: firstName, lastName: lastName, age: age)
        return copy
    }
}

Check the output of this code in Playground

let paul = Person(firstName: "Paul", lastName: "Hudson", age: 36)
let sophie = paul.copy() as! Person

sophie.firstName = "Sophie"
sophie.age = 6

print("\(paul.firstName) \(paul.lastName) is \(paul.age)")
print("\(sophie.firstName) \(sophie.lastName) is \(sophie.age)")

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM