当我试图快速访问它时,弱属性给我零 [英] weak property gives me nil when i'm trying to access it swift

查看:155
本文介绍了当我试图快速访问它时,弱属性给我零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些课程:

class Song {
    var title : String = ""
    weak var album : Album?

    init() {
        self.album = Album()
    }

}

class Album {
    var title : String = ""
    var Songs : Array < Song > = []
    deinit {
        print(self , self.title)
    }
}

这应该可以正常工作,但每当我尝试从歌曲实例设置专辑的标题时,我得到专辑
的nil错误,例如如果执行以下代码:

this should works fine but whenever i try to set title for album from a song instance i get nil error for album for example if execute code below :

let s = Song()
s.title = "some title for song"
s.album!.title = "some title for album"

尝试s.album时的一些标题!.title =我得到:

when trying to s.album!.title = "" i get :


在展开可选值时意外发现nil

unexpectedly found nil while unwrapping an Optional value

在Song类中调用init的deinit函数一次

deinit function called on init in Song class once

我在这里做错了什么?我应该如何解决这个问题?

what am i doing wrong here? how should i fix this?

推荐答案

只要没有其他引用,弱属性就会变为零它所拥有的价值。在您的代码中,您为其分配了新创建的专辑值,并且不将其存储在其他任何地方。

Weak property becomes nil as soon as there's no other strong references to the value it holds. In your code you assign newly created Album value to it and do not store it anywhere else.

因此,您的弱属性保留对专辑实例的唯一引用,它将变为零分配后立即。

So you weak property holds the only reference to album instance and it will become nil immediately after assignment.

修复将取决于您使用/构建数据的方式。如果专辑存储对其歌曲的引用,那么您应首先在某处创建并存储专辑对象,然后使用它来初始化其歌曲。
如果专辑没有对其歌曲的引用(这可能很奇怪),那么你可以让专辑变量变强。

The fix would depend on the way you use/construct your data. If Album stores references to its songs then you should create and store album object somewhere first and then use it to initialize its songs. If Album has no references to its songs (which would probably be weird), then you can just make album variable strong.

这篇关于当我试图快速访问它时,弱属性给我零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆