0

I have an exception bad access code 2, when i am inserting new entity in core data.

    class func createInManagedObjectContext(moc: NSManagedObjectContext, fuel_id: Int, fuel_name: String, price: Double) -> Fuel

    {
        var fuel = NSEntityDescription.insertNewObjectForEntityForName("GasStation", inManagedObjectContext: moc) as Fuel //exception - EXC_ARM_BREAKPOINT

        moc.performBlockAndWait { () -> Void in
            fuel.fuel_id = fuel_id
            fuel.fuel_name = fuel_name
            fuel.price = price

        }

//        dispatch_async(dispatch_get_main_queue(), { () -> Void in
//            fuel.fuel_id = fuel_id
//            fuel.fuel_name = fuel_name
//            fuel.price = price
//
//        })


        return fuel
    }

and

if let prices = info["prices"] as? NSArray {
     for price in prices {
     let fuelId : Int = price["fuel_id"] as Int
     var fuelPriceString : String = price["price"] as String
     let fuelName : String = price["fuel_name"] as String
     var fuelPrice : Double = NSString(string:fuelPriceString).doubleValue


     println(managedObjectContext)

     var fuel =
Fuel.createInManagedObjectContext(managedObjectContext!,fuel_id: Int64(fuelId), fuel_name: fuelName, price:fuelPrice)// exception
     fuelSet.append(fuel)
          }
     println(fuelSet)
}

I tried to see if context is nil, but it has address. i read some articles about zombies tool for detecting what exact exception u have and why, but there is no instructions. Can someone help me, cause i am really stuck?

Pavel Zagorskyy
  • 135
  • 2
  • 11
  • Possible duplicate of http://stackoverflow.com/questions/24350686/how-to-use-core-data-integer-64-with-swift-int64 – Jody Hagins Feb 25 '15 at 13:44

1 Answers1

0

You need to ensure one of the following:

  • your managedObjectContext is a NSMainQueueConcurrencyType one (rather than NSPrivateQueueConcurrencyType )
  • Perform the changes in a performBlock or performBlockAndWait

So:

var fuel
moc.performBlockAndWait { () -> Void in
    fuel = NSEntityDescription.insertNewObjectForEntityForName("GasStation", inManagedObjectContext: moc) as Fuel
    fuel.fuel_id = fuel_id
    fuel.fuel_name = fuel_name
    fuel.price = price
}
return fuel

(hopefully easy to translate to Swift) Basically, if you're in a private queue context, make sure you don't access it from the main thread (e.g. UI code etc), this applies to reads and writes. Be careful reading from the newly created object back in the main thread if you created it in a private queue.

I recommend to spend a bit of time reading about it and playing around seeing where the pain-points are. It will save you time in the long run!

http://code.tutsplus.com/tutorials/core-data-from-scratch-concurrency--cms-22131 https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdConcurrency.html

button
  • 666
  • 6
  • 14