I'm a little confused regarding Swift's memory management. Can someone explain to me how come kid1 always stays at the same memory address? Even when I do kid1=kid2 or initialize a new object?
相关问题
- What uses more memory in c++? An 2 ints or 2 funct
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Achieving the equivalent of a variable-length (loc
- Get the NSRange for the visible text after scroll
相关文章
- Using if let syntax in switch statement
- Why are memory addresses incremented by 4 in MIPS?
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
Your code prints the memory location of the
kid1
variable, and that does not change if you assign a new value to the variable.If
Kid
is a reference type (class) then you can useObjectIdentifier
to get a unique identifier for the class instance that the variable references:The object identifier happens to be the address of the pointed-to instance, but that is an undocumented implementation detail. If you need to convert an object reference to a real pointer then you can do (compare How to cast self to UnsafeMutablePointer<Void> type in swift)
Why
kid1
is pointing to the sameMemoryAddress
each time?In general, a class is a reference type. Which means, all instances of a class will share a single copy of data.
I.e, it's like a mutable data, if you change a data at any once instance of class, then it will affect that change to all its dependent instances.
It mainly deals with the memory addresses.
I think you have declared your class like below:
then for
var kid1 = Kid(name: "A")
: Forkid1
instance it will assign some memory address, say<Kid: 0x60400024b400>
var kid2 = Kid(name: "B")
: Forkid2
instance it will assign some other memory address, say<Kid: 0x60400024b760>
when you do
kid1 =kid2
:kid1
memory address will get changed tokid2
memory address. So,kid1
andkid2
will pointing to same memory address.kid1.name = "C"
: now if a changekid1.name
,..it will reflect tokid2.name
value also,because both are pointing to same memory address.Therefore you get: