Michael Bernat
Michael Bernat

Reputation: 646

NSData method mutableCopy() does not work as objC [... mutableCopy]?

Swift 4:

let d1 = NSData(base64Encoded: "wAEP/w==")!
let d2 = d1.mutableCopy() as! NSMutableData

d1 and d2 points to the same address in memory, however I would expect that mutableCopy() will work as objC [d1 mutableCopy] - eg. create new instance of NSMutableData object.

Do I really do something wrong, or Swift works differently?

Upvotes: 0

Views: 145

Answers (1)

barbarity
barbarity

Reputation: 2488

No, d1 and d2 are not pointing to the same address in memory. And it is creating a different instance.

What you are seeing on the right of the playground isn't the address of the object, it's the representation of the Data you have. To prove it's creating a different instance, just try this code:

let d1 = NSData(base64Encoded: "wAEP/w==")!
let d2 = d1.mutableCopy() as! NSMutableData
d2.append(Data(base64Encoded: "wAEP")!)
print(d1)
print(d2)

If they were the same instance, d2 would print the same as d1

Upvotes: 2

Related Questions