Philsen3000
Philsen3000

Reputation: 107

weak variable is intermediately nil

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

Upvotes: 4

Views: 3995

Answers (2)

Volodymyr
Volodymyr

Reputation: 1205

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

Upvotes: 1

Duncan C
Duncan C

Reputation: 131481

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

Upvotes: 3

Related Questions