码迷,mamicode.com
首页 > 编程语言 > 详细

Swift类实例与循环引用的解决

时间:2015-08-20 18:48:31      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

代码-情形1:

// 两个属性的值都允许为nil,这种场景最适合用弱引用来解决
class Person {
    let name: String
    init(name: String) {
        self.name = name
    }
    
    // 弱引用
    var apartment: Apartment?
    deinit {
        print("\(name) is being deinitialized")
    }
}

class Apartment {
    let number: Int
    
    init(number: Int) {
        self.number = number
    }
    
    // 弱引用
    weak var tenant: Person?
    
    deinit {
        print("Apartment #\(number) is being deinitialized")
    }
}

var John: Person? = Person(name: "John")
var Number73: Apartment? = Apartment(number: 73)

John!.apartment = Number73
Number73!.tenant = John

John = nil
Number73 = nil

 

代码-情形2:

// 一个属性的值允许为nil,而另一个属性的值不允许为nil,这种场景最适合通过无主引用来解决
class Customer {
    let name: String
    var card: CreditCard?
    init(name: String) {
        self.name = name
    }
    deinit {
        print("\(name) is being deinitialized")
    }
}

class CreditCard {
    let number: UInt64
    // 无主引用,不会对实例产生强引用
    unowned let customer: Customer
    init(number: UInt64, customer: Customer) {
        self.number = number
        self.customer = customer
    }
    deinit {
        print("Card #\(number) is being deinitialized")
    }
}

var john: Customer? = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)

john = nil

 

代码-情形3:

// 两个属性都必须有值,并且初始化完成后永远不会为nil
// 这种场景最适合通过一个类使用无主属性,而另外一个类使用隐式解析可选属性来解决
class Country {
    let name: String
    var capitalCity: City!
    init(name: String, capitalName: String) {
        self.name = name
        self.capitalCity = City(name: capitalName, country: self)
    }
    deinit {
        print("Country named \(name) is being deinitialized")
    }
}

class City {
    let name: String
    unowned let country: Country
    init(name: String, country: Country) {
        self.name = name
        self.country = country
    }
    deinit {
        print("City named \(name) is being deinitialized")
    }
}

var country: Country? = Country(name: "Canada", capitalName: "Ottawa")

country = nil

 

Swift类实例与循环引用的解决

标签:

原文地址:http://www.cnblogs.com/loftyspirit/p/4745840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!