[英]Swift's memory management
Your code prints the memory location of the kid1
variable, and that does not change if you assign a new value to the variable. 您的代码打印了
kid1
变量的内存位置,如果kid1
变量赋值,则不会更改。
If Kid
is a reference type (class) then you can use ObjectIdentifier
to get a unique identifier for the class instance that the variable references: 如果
Kid
是引用类型(类),那么您可以使用ObjectIdentifier
来获取变量引用的类实例的唯一标识符:
var kid1 = Kid(name: "A")
var kid2 = Kid(name: "B")
print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06220)
print(ObjectIdentifier(kid2)) // ObjectIdentifier(0x0000000100b06250)
kid1 = kid2
print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06250)
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 )
如果你需要将对象引用转换为真实的指针,那么你可以做(比较如何在swift中将self转换为UnsafeMutablePointer <Void>类型 )
print(Unmanaged.passUnretained(kid1).toOpaque())
Why kid1
is pointing to the same MemoryAddress
each time? 为什么
kid1
都指向相同的MemoryAddress
?
In general, a class is a reference type. 通常,类是引用类型。 Which means, all instances of a class will share a single copy of data.
这意味着,类的所有实例将共享一个数据副本。
Ie, 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: 我想你已经宣布你的课程如下:
class Kid {
var name: String?
init(name:String) {
self.name = name
}
}
then for 那么
var kid1 = Kid(name: "A")
: For kid1
instance it will assign some memory address, say <Kid: 0x60400024b400>
var kid1 = Kid(name: "A")
:对于kid1
实例,它将分配一些内存地址,比如说<Kid: 0x60400024b400>
var kid2 = Kid(name: "B")
: For kid2
instance it will assign some other memory address, say <Kid: 0x60400024b760>
var kid2 = Kid(name: "B")
:对于kid2
实例,它会分配一些其他的内存地址,比如说<Kid: 0x60400024b760>
when you do kid1 =kid2
: kid1
memory address will get changed to kid2
memory address. 当你做
kid1 =kid2
: kid1
内存地址将被改为kid2
内存地址。 So, kid1
and kid2
will pointing to same memory address. 因此,
kid1
和kid2
将指向相同的内存地址。
kid1.name = "C"
: now if a change kid1.name
,..it will reflect to kid2.name
value also,because both are pointing to same memory address. kid1.name = "C"
:现在如果更改kid1.name
,..它也会反映到kid2.name
值,因为两者都指向相同的内存地址。
Therefore you get: 因此你得到:
kid1.name == "C"
kid2.name == "C"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.