weak variable is intermediately nil

*爱你&永不变心* 提交于 2019-12-10 20:11:06

问题


when are weak variable gets nil?

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

getting always:

fatal error: unexpectedly found nil while unwrapping an Optional value

Xcode error


回答1:


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.

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!))



回答2:


Local variables should pretty much always be strong. That way if you create an object and save it to a local variable, the strong reference provided by the local variable keeps the object alive. When you exit the current scope, the local variable is popped off the stack and it's strong reference goes away.

In your code, the SKSpriteNode initWithTexture method creates a new sprite kit node and returns it. At the point the function returns, the init function no longer has a strong reference to the object. You save the result of the initWithTexture call to a weak variable, so at the end of that statement, there are NO strong references to the object. It gets released immediately. That is why it becomes nil.

Solution: change your local variable to strong. Change:

weak var backgroundNode = SKSpriteNode(texture: SKTexture(image: initialBackgroundImage!))

to

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


来源:https://stackoverflow.com/questions/35091284/weak-variable-is-intermediately-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!