class person
deinit
}var reference1:person?
var reference2:person?
var reference3:person?
reference1 = person(name: "iyaqi") //此時會列印:person:iyaqi is being initialized
reference2 = reference1
reference3 = reference2
reference3 = nil
reference2 = nil
reference1 = nil // iyaqi is being deinitialized 在這才回銷毀,因為有三個指標指向這塊記憶體位址。arc 會再沒有強指向的時候銷毀該物件,收回位址
1.迴圈強引用class customer
var apartment:apartment?
deinit
}class apartment
weak var customer:customer? // 加個weak 相當於apartment 的customer物件是弱引用,這樣就不會引起強引用
deinit
}var customer:customer?
var apartment:apartment?
customer = customer.init(name: "iyaiq")
apartment = apartment(unit: "19900619")
customer!.apartment = apartment
apartment!.customer = customer
//這兩個操作不會觸發任何deinit動作,因為相互引用,不會釋放 加個weak ,就能解決這個問題
customer = nil
apartment = nil
//無主引用
class people
deinit
}class creditcard
deinit
}var people :people?
people = people(name: "iyaqi")
let card = creditcard(number: 1990, people: people!)
people!.card = card
people = nil //當people銷毀的時候,這兩個物件都會被銷毀 apartment 19900619 is being deinited,iyaqi is being deinitialized
2.無主引用和隱式解析class country
deinit
}class city
deinit
}var country:country? = country(name: "china", city: "beijing")
var city:city? = city(name: "beijing", country:country!)
print("\(city!.name)") //beijing
city = nil //city:beijing is deinit
country = nil //country:china is deinit
3.閉包引起的迴圈強引用class htmlelement else
}init(name:string,text:string? = nil)
deinit
}var htmlelement:htmlelement? = htmlelement(name:"p")
let defaulttext = "some default text"
htmlelement!.ashtml =
print(htmlelement!.ashtml()) // some default text
htmlelement = nil//htmlelement is deinited 此時會觸發deinit,因為在閉包沒有使用self
var testhtmlelement:htmlelement? = htmlelement(name:"p",text:"hello world")
print(testhtmlelement!.ashtml()) //hello world
testhtmlelement = nil //此時並不會觸發deinit,因為在閉包中使用了self
解決在閉包中引用了當前例項的方法1.定義捕獲列表:捕獲列表和關鍵字in放在閉包最開始
2.弱引用和無主引用。
2.1在閉包和捕獲的例項總是互相引用並且總是同時銷毀時,將閉包內的捕獲定義為無主引用
2.2在**獲的引用可能會變為nil時,將閉包內的捕獲定義為弱引用。弱引用總是可選型別,並且當引用的例項被銷毀後,弱引用的值會自動置為nil
class testprotocol
class testclass
init(delegate:testprotocol?)
}let testprotocol = testprotocol()
var testclass = testclass(delegate: testprotocol)
print(testclass.someclosure()) //testclass's delegate is : testprotocol
swift學習筆記之自動引用計數
swift使用自動引用計數 arc 來管理應用程式的記憶體使用。這表示記憶體管理已經是swift的一部分,在大多數情況下,你並不需要考慮記憶體的管理。當例項並不再被需要時,arc會自動釋放這些例項所使用的記憶體。另外需要注意的 引用計數僅僅作用於類例項上。結構和列舉是值型別,而非引用型別,所以不能被...
swift自動引用計數
在少數情況下,arc為了能幫助你管理記憶體,需要更多的關於你的 之間關係的資訊 引用計數僅僅應用於類的例項,結構體和列舉型別是值型別,不是引用型別,也不是通過引用的方式儲存和傳遞 為了使之成為可能,無論你將例項賦值給屬性,常量或者是變數,屬性,常量或者變數,都會對此例項建立強引用。之所以稱之為強引用...
swift基礎之自動引用計數
自動引用計數 分為 自動引用計數概念 引用計數策略 如何解決迴圈引用 閉包的迴圈引用 使用的到的關鍵字 weak 弱引用不會影響引用計數,一般時 optional unowned 無主引用不會影響引用計數,一般時 非optional 概念 在swift中 自動引用計數是例項的被引用次數儲存起來,當被...