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?
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 thisvar friend: User?
about retain cycles, you will get a retain cycle only if
self.friend.friend = self
orself.friend = self
you can always check if an object is getting deallocated implementing
deinit
methodExamples
case1
Result
case2
Result