0
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?

Dilip Tiwari
  • 1,441
  • 18
  • 31

3 Answers3

0

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
ManuRaphy
  • 361
  • 1
  • 13
0

When you want the same address for different values

USE =

for eg.

var ogArray : NSMutableArray() var tempArray = ogArray

0

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

user3354805
  • 135
  • 8