Swift--15内存管理

前端之家收集整理的这篇文章主要介绍了Swift--15内存管理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//Swift的内存管理

class Human {

deinit {

print("对象即将释放")

}

}


var xiaoMing: Human? = Human()

var xiaoWang: Human? = xiaoMing


if xiaoMing === xiaoWang {

print("同一对象")

} else {

print("不同对象")

}


xiaoMing = nil

xiaoWang = nil


//弱引用(weak)

class Person {

var name: String

init (name: String) {

self.name = name

}

deinit {

print("\(name) 被释放")

}

var apartment: Apartment?

}

class Apartment {

var number: Int

init(number: Int) {

self.number = number

}

deinit {

print("#\(number)公寓被释放")

}

//公寓可能没有主人,建议使用weak,这样可以避免强引用

//当引用的实例销毁时,ARC会将该引用设置为nil

weak var tenant: Person?

}


//定义约翰和73号公寓

var john: Person?

var num73: Apartment?


john = Person(name: "John")

num73 = Apartment(number: 73)


#if true

//此时会造成循环强引用,两对象都无法释放

john?.apartment = num73

num73?.tenant = john

#endif


john = nil

//当引用的实例销毁时,ARC会将该引用设置为nil

print(num73?.tenant as Any) //nil


num73 = nil


//无主引用(unowned)

class Customer {

var name: String

var card: CreditCard?

init(name: String) {

self.name = name

}

deinit {

print("Customer: \(name) 被释放")

}

}

class CreditCard {

var number: Int

//若该引用始终有值,建议使用unowned,可以避免强引用

unowned let customer: Customer

init(number: Int,customer: Customer) {

self.number = number

self.customer = customer

}

deinit {

print("Card: #\(number) 被释放")

}

}


var tom: Customer?

tom = Customer(name: "Tom")

tom?.card = CreditCard(number: 12345678,customer: tom!)


tom = nil


//闭包引起的强引用

class Student {

var name: String

init (name: String) {

self.name = name

}

deinit {

print("Student \(name) 被释放")

}

lazy var fullName: ()->String = {

//闭包中使用self,会造成强引用(即使多次使用self也只是引用一次)

[unowned self] in

return "王氏.\(self.name)"

}

}


var stu: Student? = Student(name: "Lucy")

var fullName = stu?.fullName

//stu = nil

print(fullName!())

猜你在找的Swift相关文章