內(nèi)存管理
跟OC一樣阳啥,Swift也是采取基于引用計(jì)數(shù)的ARC內(nèi)存管理方案(針對(duì)堆空間)
Swift的ARC中有3種引用
□ 強(qiáng)引用(strong reference):默認(rèn)情況下飒赃,引用都是強(qiáng)引用
□ 弱引用(weak reference):通過(guò)weak定義弱引用 ?? 必須是可選類型的var,因?yàn)閷?shí)例銷毀后国撵,ARC會(huì)自動(dòng)將弱引用設(shè)置為nil
?? ARC自動(dòng)給弱引用設(shè)置nil時(shí),不會(huì)觸發(fā)屬性觀察器
□ 無(wú)主引用(unowned reference):通過(guò)unowned定義無(wú)主引用 ?? 不會(huì)產(chǎn)生強(qiáng)引用民鼓,實(shí)例銷毀后仍然存儲(chǔ)著實(shí)例的內(nèi)存地址(類似于OC中的unsafe_unretained) ?? 試圖在實(shí)例銷毀后訪問(wèn)無(wú)主引用矛物,會(huì)產(chǎn)生運(yùn)行時(shí)錯(cuò)誤(野指針) ? Fatal error: Attempted to read an unowned reference but object 0x0 was already deallocated
weak、unowned的使用限制
- weak路翻、unowned只能用在類實(shí)例上面
protocol Livable : AnyObject {}
class Person {}
weak var p0: Person?
weak var p1: AnyObject?
weak var p2: Livable?
unowned var p10: Person?
unowned var p11: AnyObject?
unowned var p12: Livable?
Autoreleasepool
public func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result
autoreleasepool {
let p = MJPerson(age: 20, name: "Jack")
p.run()
}
循環(huán)引用(Reference Cycle)
- weak狈癞、unowned 都能解決循環(huán)引用的問(wèn)題,unowned 要比weak 少一些性能消耗
□ 在生命周期中可能會(huì)變?yōu)?nil 的使用 weak
□ 初始化賦值后再也不會(huì)變?yōu)?nil 的使用 unowned
閉包的循環(huán)引用
閉包表達(dá)式默認(rèn)會(huì)對(duì)用到的外層對(duì)象產(chǎn)生額外的強(qiáng)引用(對(duì)外層對(duì)象進(jìn)行了retain操作)
下面代碼會(huì)產(chǎn)生循環(huán)引用茂契,導(dǎo)致Person對(duì)象無(wú)法釋放(看不到Person的deinit被調(diào)用)
class Person {
var fn: (() -> ())?
func run() { print("run") }
deinit { print("deinit") }
}
func test() {
let p = Person()
p.fn = { p.run() }
}
test()
- 在閉包表達(dá)式的捕獲列表聲明weak或unowned引用蝶桶,解決循環(huán)引用問(wèn)題
p.fn = {
[weak p] in
p?.run()
}
p.fn = {
[unowned p] in
p.run()
}
p.fn = {
[weak wp = p, unowned up = p, a = 10 + 20] in
wp?.run()
}
閉包的循環(huán)引用
- 如果想在定義閉包屬性的同時(shí)引用self,這個(gè)閉包必須是lazy的(因?yàn)樵趯?shí)例初始化完畢之后才能引用self)
class Person {
lazy var fn: (() -> ()) = {
[weak self] in
self?.run()
}
func run() { print("run") }
deinit { print("deinit") }
}
□ 左邊的閉包fn內(nèi)部如果用到了實(shí)例成員(屬性掉冶、方法)
□ 編譯器會(huì)強(qiáng)制要求明確寫出self
□ 如果lazy屬性是閉包調(diào)用的結(jié)果真竖,那么不用考慮循環(huán)引用的問(wèn)題(因?yàn)殚]包調(diào)用后,閉包的生命周期就結(jié)束了)
class Person {
var age: Int = 0
lazy var getAge: Int = {
self.age
}()
deinit { print("deinit") }
}
@escaping
非逃逸閉包厌小、逃逸閉包恢共,一般都是當(dāng)做參數(shù)傳遞給函數(shù)
非逃逸閉包:閉包調(diào)用發(fā)生在函數(shù)結(jié)束前,閉包調(diào)用在函數(shù)作用域內(nèi)
逃逸閉包:閉包有可能在函數(shù)結(jié)束后調(diào)用璧亚,閉包調(diào)用逃離了函數(shù)的作用域讨韭,需要通過(guò)@escaping聲明
import Dispatch
typealias Fn = () -> ()
// fn是非逃逸閉包
func test1(_ fn: Fn) { fn() }
// fn是逃逸閉包
var gFn: Fn?
func test2(_ fn: @escaping Fn) { gFn = fn }
// fn是逃逸閉包
func test3(_ fn: @escaping Fn) {
DispatchQueue.global().async {
fn()
}
}
class Person {
var fn: Fn
// fn是逃逸閉包
init(fn: @escaping Fn) {
self.fn = fn
}
func run() {
// DispatchQueue.global().async也是一個(gè)逃逸閉包
// 它用到了實(shí)例成員(屬性、方法)涨岁,編譯器會(huì)強(qiáng)制要求明確寫出self
DispatchQueue.global().async {
self.fn()
}
}
}
逃逸閉包的注意點(diǎn)
- 逃逸閉包不可以捕獲inout參數(shù)
typealias Fn = () -> ()
func other1(_ fn: Fn) { fn() }
func other2(_ fn: @escaping Fn) { fn() }
func test(value: inout Int) -> Fn {
other1 { value += 1 }
// error: 逃逸閉包不能捕獲inout參數(shù)
other2 { value += 1 }
func plus() { value += 1 }
// error: 逃逸閉包不能捕獲inout參數(shù)
return plus
}
內(nèi)存訪問(wèn)沖突(Conflicting Access to Memory)
- 內(nèi)存訪問(wèn)沖突會(huì)在兩個(gè)訪問(wèn)滿足下列條件時(shí)發(fā)生:
□ 至少一個(gè)是寫入操作
□ 它們?cè)L問(wèn)的是同一塊內(nèi)存
□ 它們的訪問(wèn)時(shí)間重疊(比如在同一個(gè)函數(shù)內(nèi))
// 不存在內(nèi)存訪問(wèn)沖突
func plus(_ num: inout Int) -> Int { num + 1 }
var number = 1
number = plus(&number)
// 存在內(nèi)存訪問(wèn)沖突
// Simultaneous accesses to 0x0, but modification requires exclusive access var step = 1
func increment(_ num: inout Int) { num += step }
increment(&step)
// 解決內(nèi)存訪問(wèn)沖突
var copyOfStep = step increment(©OfStep) step = copyOfStep
內(nèi)存訪問(wèn)沖突
func balance(_ x: inout Int, _ y: inout Int) {
let sum = x + y
x = sum / 2
y = sum - x
}
var num1 = 42
var num2 = 30
balance(&num1, &num2) // OK
balance(&num1, &num1) // Error
struct Player {
var name: String
var health: Int
var energy: Int
mutating func shareHealth(with teammate: inout Player) {
balance(&teammate.health, &health)
}
}
var oscar = Player(name: "Oscar", health: 10, energy: 10)
var maria = Player(name: "Maria", health: 5, energy: 10)
oscar.shareHealth(with: &maria) // OK
oscar.shareHealth(with: &oscar) // Error
var tulpe = (health: 10, energy: 20)
// Error
balance(&tulpe.health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
// Error
balance(&holly.health, &holly.energy)
內(nèi)存訪問(wèn)沖突
如果下面的條件可以滿足拐袜,就說(shuō)明重疊訪問(wèn)結(jié)構(gòu)體的屬性是安全的
你只訪問(wèn)實(shí)例存儲(chǔ)屬性,不是計(jì)算屬性或者類屬性
結(jié)構(gòu)體是局部變量而非全局變量
結(jié)構(gòu)體要么沒(méi)有被閉包捕獲要么只被非逃逸閉包捕獲
// Ok
func test() {
var tulpe = (health: 10, energy: 20)
balance(&tulpe.health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
balance(&holly.health, &holly.energy)
}
test()
指針
-
Swift中也有專門的指針類型梢薪,這些都被定性為“Unsafe”(不安全的)蹬铺,常見(jiàn)的有以下4種類型
UnsafePointer<Pointee> 類似于 const Pointee *
UnsafeMutablePointer<Pointee> 類似于 Pointee *
UnsafeRawPointer 類似于 const void *
UnsafeMutableRawPointer 類似于 void *
var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>) {
ptr.pointee += 10
}
func test2(_ ptr: UnsafePointer<Int>) {
print(ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20
var age = 10
func test3(_ ptr: UnsafeMutableRawPointer) {
ptr.storeBytes(of: 20, as: Int.self)
}
func test4(_ ptr: UnsafeRawPointer) {
print(ptr.load(as: Int.self))
}
test3(&age)
test4(&age) // 20
print(age) // 20
指針的應(yīng)用示例
var arr = NSArray(objects: 11, 22, 33, 44)
arr.enumerateObjects { (obj, idx, stop) in
print(idx, obj)
if idx == 2 { // 下標(biāo)為2就停止遍歷
stop.pointee = true
}
}
var arr = NSArray(objects: 11, 22, 33, 44)
for (idx, obj) in arr.enumerated() {
print(idx, obj)
if idx == 2 {
break
}
}
獲得指向某個(gè)變量的指針
var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age) { $0 }
var ptr2 = withUnsafePointer(to: &age) { $0 }
ptr1.pointee = 22
print(ptr2.pointee) // 22
print(age) // 22
var ptr3 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) }
var ptr4 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) }
ptr3.storeBytes(of: 33, as: Int.self)
print(ptr4.load(as: Int.self)) // 33
print(age) // 33
獲得指向堆空間實(shí)例的指針
class Person {}
var person = Person()
var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
var heapPtr = UnsafeRawPointer(bitPattern: ptr.load(as: UInt.self))
print(heapPtr!)
創(chuàng)建指針
var ptr = UnsafeRawPointer(bitPattern: 0x100001234)
// 創(chuàng)建
var ptr = malloc(16)
// 存
ptr?.storeBytes(of: 11, as: Int.self)
ptr?.storeBytes(of: 22, toByteOffset: 8, as: Int.self)
// 取
print((ptr?.load(as: Int.self))!) // 11
print((ptr?.load(fromByteOffset: 8, as: Int.self))!) // 22
// 銷毀
free(ptr)
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.storeBytes(of: 11, as: Int.self)
ptr.advanced(by: 8).storeBytes(of: 22, as: Int.self)
print(ptr.load(as: Int.self)) // 11
print(ptr.advanced(by: 8).load(as: Int.self)) // 22
ptr.deallocate()
var ptr = UnsafeMutablePointer<Int>.allocate(capacity: 3)
ptr.initialize(to: 11)
ptr.successor().initialize(to: 22)
ptr.successor().successor().initialize(to: 33)
print(ptr.pointee) // 11
print((ptr + 1).pointee) // 22
print((ptr + 2).pointee) // 33
print(ptr[0]) // 11
print(ptr[1]) // 22
print(ptr[2]) // 33
ptr.deinitialize(count: 3)
ptr.deallocate()
創(chuàng)建指針
class Person {
var age: Int
var name: String
init(age: Int, name: String) {
self.age = age
self.name = name
}
deinit { print(name, "deinit")
}
var ptr = UnsafeMutablePointer<Person>.allocate(capacity: 3)
ptr.initialize(to: Person(age: 10, name: "Jack"))
(ptr + 1).initialize(to: Person(age: 11, name: "Rose"))
(ptr + 2).initialize(to: Person(age: 12, name: "Kate"))
// Jack deinit
// Rose deinit
// Kate deinit
ptr.deinitialize(count: 3)
ptr.deallocate()
指針之間的轉(zhuǎn)換
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.assumingMemoryBound(to: Int.self).pointee = 11
(ptr + 8).assumingMemoryBound(to: Double.self).pointee = 22.0
print(unsafeBitCast(ptr, to: UnsafePointer<Int>.self).pointee) // 11
print(unsafeBitCast(ptr + 8, to: UnsafePointer<Double>.self).pointee) // 22.0
ptr.deallocate()
unsafeBitCast是忽略數(shù)據(jù)類型的強(qiáng)制轉(zhuǎn)換,不會(huì)因?yàn)閿?shù)據(jù)類型的變化而改變?cè)瓉?lái)的內(nèi)存數(shù)據(jù)
類似于C++中的reinterpret_cast
class Person {}
var person = Person()
var ptr = unsafeBitCast(person, to: UnsafeRawPointer.self) print(ptr)