无法解码弱变量中的值 [英] 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
}
}
User类具有一个Friend属性,该属性将再次是用户类型。因此,为了避免任何保留周期,我将其视为弱变量。但是,当JSONDecoder解码json时,用户实例的friend属性始终为nil。如果我在这种情况下把朋友当作弱者是不对的?如果正确,则如何将值插入到用户的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.
也请阅读此弱变量介于中间nil 。如果我不使用弱,会不会有保留周期?
Also read this weak variable is intermediately nil. Will there be any retain cycles if i donot use weak?
推荐答案
在这种情况下,您的朋友变量必须较强,否则将在使用编码器方法进行的初始化结束后实例化并释放,将弱的var朋友:User?
更改为此 var的朋友:User?
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?
关于保留周期,只有 self.friend.friend = self
,您才会获得保留周期或 self.friend = self
about retain cycles, you will get a retain cycle only if self.friend.friend = self
or self.friend = self
您始终可以检查对象是否在实现 deinit
方法
you can always check if an object is getting deallocated implementing deinit
method
示例
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
}
结果
user1被释放
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
}
结果
user1 don 't取消分配->保留周期问题
user1 don't deallocated -> Retain Cycle Issue
这篇关于无法解码弱变量中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!