Search code examples
iossprite-kitexc-bad-accessnsthreadsknode

iOS7 SpriteKit crash after spending time in NSThread


I'm currently writing a turn-based SpriteKit game with one or more AI players. Each AI takes its turn one at a time, and finds their own solution using a shared solutionFinder instance, but does this in a detached thread as it sometimes takes a few seconds...

[NSThread detachNewThreadSelector:@selector(findSolution:)
    toTarget:self.scene.solutionFinder 
    withObject:self];

...where self is the current AI player, and scene is the parent SKScene, which contains an SKNode that has the AI players as children. When the thread only runs for a few milliseconds, everything is fine, but when the thread runs for a few seconds, very rarely I get an EXC_BAD_ACCESS exception in the SKScene's -(void)update:(CFTimeInterval)currentTime method.

I've added some NSLogs where the exception was thrown, and it is dereferencing the SKNode that contains the AI players that is the problem. However logging the address the pointer points to shows that it does not change from a valid access to an invalid one - is it possible that the detached thread is incorrectly releasing the SKNode when the thread finishes, or is something else going wrong?

The method called by NSThread is wrapped in an @autorelease.


Solution

  • So after trying a whole load of stuff including malloc gaurds, NSZombie, @autorelease, GCD, performSelectorInBackground and other bits and pieces I was still getting occasional crashes.

    It is fixed now though! Before the fix, the SKNode that contained all the players was exposed as a property and passed around by code that needed access, and I think this was the problem, as SpriteKit would sweep things from under my feet from time to time. Now, any objects that need to be shared between classes are shared via an NSArray that I manage myself, and after hours of stress testing the problem seems to have gone.