如果我多次初始化相同的 属性 会发生什么

what happens if I initialise the same property multiple times

我在 class 中声明 属性:

var testView: UIView!

稍后,我使用以下代码对其进行初始化:

testView = UIView(frame: myFrame)

但是,稍后,我再次初始化它:

testView = UIView(frame: myFrame)

第一个 testView 实例发生了什么? testView 现在使用两倍的内存吗?如果我重复此过程 1000 次会怎样?我可以这样做吗?

Swift 和 Object C 使用 ARC 内存管理。

除非您在别处引用第一个 UIview,否则在对 testView 的连续赋值中,第一个 UIView 引用计数将变为 0,并且其内存将被释放。

因此 testView 将始终使用一个 UIView 所需的内存,即使您重复该过程 1000 次。

在这种情况下,您只需覆盖这些值。你可以做 1000 次,但它毫无意义。它只是花费了一些 CPU 容量。

Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

就像我将字符串重新初始化为不同的值一样,原始值会被替换,所以如果我将字符串分配给与旧值相同的值,它会被替换,在重新分配 UIView 以相同的值替换旧值。为什么需要用相同的值替换旧值?