本文和大家分享的主要是swift
中內(nèi)存管理相關(guān)內(nèi)容,一起來看看吧,希望對(duì)大家
學(xué)習(xí)swift有所幫助。
Swift
是自動(dòng)管理內(nèi)存的。這意味著,你不需要主動(dòng)釋放內(nèi)存。
比如Foo
內(nèi)包含的
Bar
,可以隨同
Foo
一起被釋放:
import UIKit@UIApplicationMain
class
AppDelegate:
UIResponder,
UIApplicationDelegate {
var window : UIWindow?
func
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Foo()
return true
}
}
class
Foo {
let bar: Bar
init() {
bar = Bar()
}
deinit {
print("Foo exit")
}
}
class
Bar {
deinit {
print("Bar exit")
}
}
執(zhí)行此代碼,會(huì)打?。?/span>
Foo
exit
Bar
exit
可見Foo
和
Bar
都是自動(dòng)釋放的。作為程序員,你不需要做任何內(nèi)存的主動(dòng)釋放。
但是,有一種特殊情況,叫做雙向引用,導(dǎo)致釋放A
時(shí),需要釋放
B
,而
B
又引用了
A
,那么兩個(gè)都無法被釋放:
class
Foo {
let bar: Bar
init() {
bar = Bar()
bar.foo =
self
}
deinit {
print("Foo exit")
}
}
class
Bar {
var foo: Foo? = nil
deinit {
print("Bar exit")
}
}
此代碼只會(huì)打?。?/span>
App
exit
此時(shí),需要做的就是把這個(gè)雙向引用中的一個(gè)設(shè)置為weak
,表示的意思是盡管我持有這個(gè)引用,但是釋放的時(shí)候,卻無需考慮此對(duì)象的釋放。
import UIKit@UIApplicationMain
class
AppDelegate:
UIResponder,
UIApplicationDelegate {
var window : UIWindow?
func
application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Baz()
print("App exit")
return true
}
}
typealias Bar = (()->Void)
class
Foo {
func
work(_ bar : Bar) {
bar()
}
deinit {
print("Foo exit")
}
}
class
Baz {
var a : String?
init (){
a = "1"
let f = Foo()
f.work(){[
weak
self]()
in
print(
self?.a)
}
}
}
當(dāng)然,不標(biāo)記也是不行的,因?yàn)榫幾g器就不會(huì)通過,它要求只要引用了self
,就必須標(biāo)記。
來源:
稀土掘金