1

I have a location-based app that gets location every 1 second, and saves a batch of the locations at a time to the CoreData DB so as not to make the locations array too large. However, for some reason it crashes with EXC_BAD_ACCESS even though I use dispatch_async on a SERIAL QUEUE:

Created a global serial custom queue like this:

var MyCustomQueue : dispatch_queue_t = 
dispatch_queue_create("uniqueID.for.custom.queue", DISPATCH_QUEUE_SERIAL);

in the didUpdateToLocation protocol function, I have this bit of code that saves the latest batch of CLLocation items onto the disk, if the batch size is greater than a preset number:

if(myLocations.count == MAX_LOCATIONS_BUFFER)
{
    dispatch_async(MyCustomQueue)
    {

        for myLocation in self.myLocations
        {
        // the next line is where it crashes with EXC_BAD_ACCESS
            newLocation = NSEntityDescription.insertNewObjectForEntityForName(locationEntityName, inManagedObjectContext: context as NSManagedObjectContext) ;
            newLocation.setValue(..)
            // all the code to set the attributes
        }

        appDelegate.saveContext();

        dispatch_async(dispatch_get_main_queue()) {
        // once the latest batch is saved, empty the in-memory array
            self.myLocations = [];
        }

    }
}

The mystery is, isn't a SERIAL QUEUE supposed to execute all the items on it in order, even though you use dispatch_async (which simply makes the execution concurrent with the MAIN thread, that doesn't touch the SQLite data)?

Notes:

  • The crash happens at random times...sometimes it'll crash after 0.5 miles, other times after 2 miles, etc.
  • If I just take out any of the dispatch_async code (just make everything executed in order on the main thread), there is no issue.
Uzumaki Naruto
  • 547
  • 5
  • 18

1 Answers1

0

You can take a look at this link. Your issue is probably because there is no MOC at the time you are trying to insert item into it.

Core Data : inserting Objects crashed in global queue [ARC - iPhone simulator 6.1]

Community
  • 1
  • 1
mSabu
  • 31
  • 4