无法解码弱变量中的值

Not able to decode value in a weak variable

class User: Codable {

//MARK:- Properties
var firstName: String?
var lastName: String?
weak var friend: User?

enum CodingKeys: String, CodingKey {
    case firstName = "first"
    case lastName = "last"
    case friend
}

}

用户 class 有一个朋友 属性,他也是用户类型。所以为了避免任何保留循环,我把它当作弱变量。但是当 JSONDecoder 解码 json 时,用户实例的朋友 属性 总是 nil。如果我在这种情况下将朋友视为弱者是错误的?如果正确,那么该值将如何插入到用户的朋友 属性 中。

另请阅读此 。如果我不使用 weak,是否会有任何保留周期?

你的 friend 变量在这个上下文中必须是强的,如果不是那么将在你的 init with coder 方法结束后被实例化和释放,通过这个 var friend: User?

改变 weak var friend: User?

关于retain cycles,只有在self.friend.friend = selfself.friend = self

时才会得到retain cycle

您始终可以检查对象是否正在执行 deinit 方法

被释放

例子

案例1

class ViewController: UIViewController {
    var user1 : User?
    var user2 : User?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        user1 = User()

        user2 = User()
        user1?.friend = user2

        user1 = nil
    }

结果

user1 deallocated

案例2

class ViewController: UIViewController {
        var user1 : User?
        var user2 : User?
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

            user1 = User()
            user1?.friend = user1

            user1 = nil
        }

结果

user1 don't deallocated -> Retain Cycle Issue