My app consist of two view managed by tab bar controller.
The first view contains a button that downloads data from server and parse it into objects. After that is done I create core data entities based on these objects. Anytime the button is pushed, the former entities are deleted to avoid adding the same data
The second view contains table view resposible for displaying the retrieved core data entities data.
This is my method to save data:
func saveData()
{
var context:NSManagedObjectContext = self.managedObjectContext!
var error: NSError?
let entityDescription =
NSEntityDescription.entityForName("Medicine",
inManagedObjectContext: managedObjectContext!)
for element in self.loadedArray {
var medicine = Medicine(entity: entityDescription!,
insertIntoManagedObjectContext: managedObjectContext)
medicine.name = element.name
medicine.desc = element.desc
var error: NSError?
context.save(&error)
println(medicine)
}
}
this is how I delete the data
func deleteData() {
let fetchRequest = NSFetchRequest(entityName: "Medicine")
let fetchedEntities = self.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [Medicine]
for entity in fetchedEntities {
self.managedObjectContext!.deleteObject(entity)
}
self.managedObjectContext!.save(nil)
}
I save the the data once the loadedArray from downloaded data is ready
var loadedArray:[Drug] = [] {
didSet {
self.saveData()
}
}
The behaviour is nondeterministic, but the error usually occurs when I save the data, then go to table view then go back to delete/save new data. This is when the crash happens and this is the error:
I am aware of the fact that this error is relatively hard to reproduce, so I think the best way is to provide a link to project https://github.com/thedc89/MedApp (check out the latest commit)
Thanks in advance
EDIT:
this is fetched result controller in second view:
lazy var fetchedResultsController: NSFetchedResultsController = {
let medicinesFetchRequest = NSFetchRequest(entityName: "Medicine")
let primarySortDescriptor = NSSortDescriptor(key: "name.order", ascending: true)
medicinesFetchRequest.sortDescriptors = [primarySortDescriptor]
let frc = NSFetchedResultsController(
fetchRequest: medicinesFetchRequest,
managedObjectContext: self.managedObjectContext!,
sectionNameKeyPath: "name",
cacheName: nil)
frc.delegate = self
return frc
}()
Moreover, for some reason the datamodel seems to be missing on github project which is really weird. However, if it was actually missing I think it would not save any data but it happens for the first time I touch the button
After downloading your project it looks like the xcdatamodel
is missing, even though it is included with the Xcode project. Other answers on SO seem to confirm similar issues for the same error: here and here.
Additionally having a property named order
is generic enough that it could be used internally. Try changing it to something like itemSortOrder
or something more descriptive to avoid conflicts.