Not able to decode value in a weak variable

2019-08-04 02:05发布

问题:

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
}

}

The User class has a friend property which will again be of type User. So in order to avoid any retain cycles, i have taken it as weak variable. But when the JSONDecoder decodes the json then the friend property of the user instance is always nil. If i am wrong in taking the friend as weak in this context?. if it is correct then how the value will be inserted in the friend property of the User.

Also read this weak variable is intermediately nil. Will there be any retain cycles if i donot use weak?

回答1:

Your friend variable must be strong in this context, if not then will be instantiated and deallocated once your init with coder method ends, change weak var friend: User? by this var friend: User?

about retain cycles, you will get a retain cycle only if self.friend.friend = self or self.friend = self

you can always check if an object is getting deallocated implementing deinit method

Examples

case1

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
    }

Result

user1 deallocated

case2

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
        }

Result

user1 don't deallocated -> Retain Cycle Issue