2015-12-14 43 views
0

我想知道,如果一個數組的值(任何類型)被自動刪除,當我用另一個替換它們時。例如,UIImage-Array的第一個值被替換爲另一個圖像。第一張圖像會發生什麼,數組以前包含了什麼?僅從RAM中刪除參考或圖像本身?在Swift中替換它們之後會發生什麼?

謝謝你的回答!

回答

0

ARC的概念將在此處使用。 第一個圖像也是一個UIImage實例,當您用第二個UIImage對象替換第一個UIImage對象時,第一個對象的強引用將被刪除。 案例1 :(現在,我假設你沒有在任何其他行中使用過這個第一個UIImage實例或者分配給任何其他變量) 因爲對象沒有任何強引用。當您用第二個圖像的對象替換它時,ARC會自動將其從內存中移除。

情況2:但如果您已將其分配給下一個變量,那麼它將不會被刪除。 讓我證明你有例子:


案例1:

var images = [UIImage]() 
images.append(UIImage(named: "elcapitan")) 
//now this first image is stored in index number 0 of the array 
//images[0] gives you access to this first image in this case 

//now i will replace the first image 
images[0] = UIImage(named: "yosemite") 

在這種情況下,ARC將自動刪除第一圖像實例,因爲它不是強從任何地方


引用情況2:

var images = [UIImage]() 
var firstImage = UIImage(named: "elcapitan") 
images.append(firstImage) 
//now this first image is stored in index number 0 of the array 
//images[0] gives you access to this first image in this case 

//now i will replace the first image 
images[0] = UIImage(named: "yosemite") 

在這種情況下,ARC無法刪除第一個圖像實例,因爲它仍然被變量firstImage引用,儘管您已經在數組中進行了替換。只有在將下一個圖像分配給firstImage變量後,實例纔會被刪除。即只有當你這樣做:firstImage = UIImage(名稱:「Windows」)

希望你得到答案:)

0

Swift使用自動引用計數(ARC)。你必須記住類和結構之間的區別。

從蘋果公司的文檔:

引用計數只適用於類的實例。結構和枚舉是值類型,而不是引用類型,不會通過引用存儲和傳遞。

簡而言之,ARC會跟蹤多少個常量,變量和屬性引用(強引用)類的實例。如果沒有引用,ARC將釋放實例並釋放內存。

class Person { 
    var name: String 

    init(name: String) { 
    self.name = name 
    } 
} 

var steve: Person? = Person(name: "Steve") // Increasing ref counter -> 1 
var sameSteve: Person? = steve // Increasing ref counter -> 2 

steve = nil // Decreasing ref counter -> 1 

print(sameSteve?.name) // prints "Steve" 

sameSteve = nil // Decreasing ref counter -> 1 

print(sameSteve?.name) // prints nil because it was deallocated 

所以,作爲UIImage是引用類型,如果從一個數組移除或更換,ARC會降低它的引用計數器。如果沒有其他變量,常量或屬性持有它,圖像將被釋放。

相關問題