Search code examples
macosswiftcrashexc-bad-access

Swift constant defined with LET sometimes produces EXC_BAD_ACCESS (EXC_I386_GPFLT) on read (OSX)


In my AppDelegate I have a constant for a statusbar icon, used when the application is busy:

class AppDelegate: NSObject, NSApplicationDelegate {

let busyImage = NSImage(named: "BusyStatus");
...

In another class I'm accessing this several times over the time the app is running. On a Macbook Air with SSD I sometimes get an

EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       EXC_I386_GPFLT

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libswiftCore.dylib              0x0000000103876cf9 swift_unknownRetain + 41
1   de.test.myapp   0x000000010304743b TestApp.AppDelegate.busyImage.getter : ObjectiveC.NSImage? (in TestApp) (AppDelegate.swift:0)
2   de.test.myapp   0x0000000102f9aa77 TestApp.Sync.(update (TestApp.Sync) -> () -> ()).(closure #2) (in TestApp) (Sync.swift:271)

The code there:

statusBarItem!.image = appDelegate!.busyImage

It's in a block called in the Main Thread:

let updateBlock: () -> () = {

    appDelegate!.statusBarItem!.image = self.appDelegate!.busyImage
        [... other code ...]
 }

 if NSThread.isMainThread()
 {
     updateBlock()
 }
 else
 {
     dispatch_sync(dispatch_get_main_queue(),updateBlock)
 }

What can cause this and how to avoid this?


Solution

  • Problem seems to be gone since swift 2. Never had this issue again and changed absolutely nothing in my code.