//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--15内存管理全部内容,希望文章能够帮你解决Swift--15内存管理所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)