Search code examples
iosxcodeios7crashxcode5

Xcode continuously crashes given thread 1 exc_bad_access (code=2 address=0x8)


after researching this error i have noticed it is code specific but any project i attempt to make, load, etc keeps giving me the same error and is always citing different parts of the code with this error message but because of the initial programs i setup, that have the exact default code nothing less nothing more and still receive the same errors i wouldn't see how adding my error log could help. Note this error occurs when using sprite kit in Xcode 5 and am running this on os x 10.8.5 thanks ahead of time for your patience, insight and hopefully an answer.


Solution

  • exc_bad_access is usually caused by what's known as a dangling pointer - accessing an object that has already been deallocated.

    To debug this, enable zombie objects by either:

    • Xcode : Edit the scheme and choose the 'Enabled Zombies' checkbox

    Edit Scheme

    • AppCode : Edit the run configuration and set the environment variable NS_ZOMBIE_ENABLED=YES

    Spend some time to learn the Objective-C reference counting memory model - retains, releases, retain-cycles and autorelease pools.

    You need to ensure that your object is being retained for as long as its being used. In ARC (Automatic Reference Counting - the default for iOS) this usually means setting a property or ivar for any object that will be used accross multiple classes - designating one object as the 'owner' of this object. It will then be deallocated along with the object that 'owns' it.

    A good way to get an understanding of the Objective-C memory model and the way ARC works, is to try using manual memory management on a pet project (something with at least 2 or 3 view controllers). Once you're comfortable with manual-memory management, ARC will be super-easy, as well as save you time, typing and prevent forgetting to release an allocated object. Most/all Objective-C fundamentals books will cover memory management. (I've forgotten the name now of the one that I read).

    A Common Cause

    Let's say you have a UIViewController and a View that you'd like to present from within your current view controller. . . its allocated as follows:

    UIViewController* anotherController = [UIViewController make];
    [self.view addSubView anotherController.view];
    

    'anotherController' will now be deallocated because its no longer used. If anotherController.view has unsafe_unretained references to anotherController it will cause an exc_bad_access.

    Infinite Recursion:

    Another cause of EXC_BAD_ACCESS is infinite recurssion, which can be debugged by adding some log statements - it will soon become apparent then!