弱变量中间为零 [英] weak variable is intermediately nil

查看:65
本文介绍了弱变量中间为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

弱变量何时变为零?

    weak var backgroundNode = SKSpriteNode(texture: SKTexture(image: initialBackgroundImage!))
    backgroundNode!.position = CGPoint(x: rootSkScene!.frame.midX, y: rootSkScene!.frame.midY)

总是得到:

致命错误:解开可选值时意外发现nil

fatal error: unexpectedly found nil while unwrapping an Optional value

Xcode错误

推荐答案

如此弱的变量意味着此引用不会使引用计数器增加一.如您所知,如果计数器等于零,则将删除对象.您在此处所做的操作-您正在创建变量,但由于它很弱,所以计数器等于0并销毁了它.还因为它很弱-当它销毁它的引用时,将自动变为nil值.

So weak variable means that this reference isn't increasing counter of references by one. As you know if counter equals zero object will be deleted. What you are doing here that - you are creating variable but as it is weak it has counter equals zero and it destroys. Also because it is weak - when it destroys its reference will automatically become nil value.

因此,我们得到的是在第一行中创建对象,该对象立即销毁,引用变为nil.在第二行中,您尝试使用此变量做一些工作,但由于它为零,因此您会得到此类异常.希望它能对您有所帮助.

So what we gets is that in first line you create object and it immediately destroys and reference becomes nil. In second line you tried to do some work with this variable but as it's nil you gets such exception. Hope it helped you.

要解决此错误,只需使用

To fix this bug just remove first line of code with

let backgroundNode = SKSpriteNode(texture: SKTexture(image: initialBackgroundImage!))

这篇关于弱变量中间为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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