2

Here is my code:

ship.runAction(SKAction.waitForDuration(5), completion: {
    self.ship.flyStraight()//retain self
})

After several days googling for the memory issues, finally I found that I had a self retain in this block. When I create the new scene before the block has run, the deinit function won't be called because the reference in the block.

I have to write in this way in my game, and what can I do to avoid this issue. What did you with code like this?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
Alfred
  • 161
  • 10
  • sorry for my poor English, any help will be appreciated! – Alfred Jan 25 '15 at 17:26
  • 5
    The Swift documentation has a section about ["Resolving Strong Reference Cycles for Closures"](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID57) ... – Martin R Jan 25 '15 at 17:31
  • Can you confirm that `deinit` is not called? since 'self' does not have a reference to the block (no strong reference cycle) wouldn't the block get reallocated when the action finishes? –  Jan 25 '15 at 17:32
  • ^ Deallocated not reallocated (sorry typo, too late to edit) –  Jan 25 '15 at 17:39
  • @Okapi "When I create the new scene before the block has run" This is why the deinit won't be called. After the block finished, deinit will be called. – Alfred Jan 26 '15 at 02:19
  • @MartinR You can edit your comment and post an answer. I added `[unowned self] in` to my code and everything looks fine! Thanks a lot! – Alfred Jan 26 '15 at 06:07

1 Answers1

6

For anyone who got the same issue. I changed my code to :

ship.runAction(SKAction.waitForDuration(5), completion: {
        [unowned self] in
        self.ship.flyStraight()        
    })

Use [unowned self] in in your block won't add a strong reference to self.

Thanks for Martin's link: "Resolving Strong Reference Cycles for Closures"

You can also take a look at this question

Community
  • 1
  • 1
Alfred
  • 161
  • 10