2016-04-25 82 views
0

我有一個非常簡單的Swift類,它只有一個靜態方法,此方法分配3個字符串數組,並通過追加這些數組中的元素來創建一個隨機字符串。內存泄漏[String]常量

下面的代碼:

public static func generateText() -> String { 

    let phraseComponent1 = [ 
     "Line 1,", 
     "Line2,", 
     "Line3,", 
     "Line4,", 
     "Line5,", 
     "Line6,"] 

    let phraseComponent2 = [ 
     "Line 1,", 
     "Line2,", 
     "Line3,", 
     "Line4,", 
     "Line5,", 
     "Line6,"] 

    let phraseComponent3 = [ 
     "Line 1,", 
     "Line2,", 
     "Line3,", 
     "Line4,", 
     "Line5,", 
     "Line6,"] 

    let componentIndex1 = Int(arc4random_uniform(UInt32(phraseComponent1.count))) 
    let componentIndex2 = Int(arc4random_uniform(UInt32(phraseComponent2.count))) 
    let componentIndex3 = Int(arc4random_uniform(UInt32(phraseComponent3.count))) 

    let phrase1 = phraseComponent1[componentIndex1] 
    let phrase2 = phraseComponent2[componentIndex2] 
    let phrase3 = phraseComponent3[componentIndex3] 

    return "\(phrase1) \(phrase2) \(phrase3)" 
} 

它發生此代碼生成第一陣列上的內存泄漏,你可以在截圖中看到: enter image description here

有人能告訴我一個理由它?以及如何解決這個問題

+1

如果你用這個方法數十億次拋棄返回值並且耗盡自動釋放池,你會看到堆增長嗎?如果沒有,這是一個誤導性的診斷輸出,你不應該擔心它。 – werediver

回答

0

我做了@werediver的提及,增加了一個巨大的循環來調用這個方法,並且堆沒有移動,也沒有泄漏的數量,所以他提到這是一個誤導性的診斷。無需採取任何行動。