Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS in NSManagedObjectContext refreshObject

I've inherited some swift code which performs a refreshObject immediately after fetching from core data. The objects being fetched have a relationship to another table. The fetch and refreshObject are inside a performBlockAndWait. The code is below. The crash appeared to begin in iOS9.

  • Any idea why the refreshObject is throwing EXC_BAD_ACCESS? What is the fix?
  • What is the purpose of doing a refreshObject immediately after the fetch? This table contains just a few rows. Is this necessary? Any downside to removing all together?

    context.performBlockAndWait {
        let className = self.className()
        let fetchRequest = NSFetchRequest(entityName: className)
        groups = (try? context.executeFetchRequest(fetchRequest)) as? [FavoriteLocationGroup]
        if groups != nil {
            groups!.sortInPlace { $0.name < $1.name }
            for group in groups! {
                context.refreshObject(group, mergeChanges: false) <<< crashes here
            }
        }
    }
    

Thanks in advance for any help you can provide!

value of context

what group is

like image 508
Justin Domnitz Avatar asked Oct 01 '15 21:10

Justin Domnitz


1 Answers

Could you try replacing sortInPlace line with

groups = groups!.sort { $0.name < $1.name }

I've hit similar issue. The app was crashing in Release mode in random place after calling sortInPlace. It seems that it causes some kind of memory corruption. sort() works well.

Upd: I was able to reproduce the crash with the following code (also crashes in OS X Cocoa apps):

import Cocoa

class MyObject {
    var x: Int?
}

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    var array = [MyObject]()

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application

        for x in 0..<100000 {
            let object = MyObject()
            object.x = x
            array.append(object)
        }
        array.sortInPlace { $0.x < $1.x } // CRASH
    }
    ...
}
like image 200
Zmey Avatar answered Sep 21 '22 00:09

Zmey