I'm using a NSFetchedResultsController to get data from CoreData and load a table view with four sections. It works perfectly when the app is run for the first time, loading a plist into CoreData and then fetching records to configure cells in 4 sections of a table.
The problem occurs when I restart the app, init values from the class appear to overwrite the values that I thought/think were stored in core data. Values that are not initialized by the class are successfully loaded by the NSFetchedResultsController.
For example, there is a value, tableSection, to define table sections. When the table loads for the very first time, it has the four sections:
BUT, if I run the app again, there is only 1 tableSection value, 'My Records' (a default value intended for when the user first creates a record):
I'm not sure, but I figure this happens when I configure the cell...
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath)
{
let record = fetchedResultsController.objectAtIndexPath(indexPath) as! Record ...}
It looks like when the custom class is initiated the init values are assigned and never overwritten by the values I thought would be in the fetchedResultsContainer. Anything not given a value in the custom class init, like the text and image, are assigned values from the fetchedResultsController:
class Record: NSManagedObject
{
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?)
{
super.init(entity: entity, insertIntoManagedObjectContext: context)
let randomBit = String(arc4random_uniform(100))
iD = NSDate().toIDTimeDateString() + "-" + randomBit + "OtR"
believers = 0
deviceTime = NSDate()
doubters = 0
eventTimeStarted = NSDate()
eventTimeEnded = NSDate()
featureImageIndex = 0
coreLocationUsed = 0
photoTaken = 0
tableSection = "My Records"
timeRecorded = deviceTime
validationScore = 0
}
}
How do I instantiate a 'Record' in a way that will overwrite the init values with the data from the fetchedResultsController? (if this is my problem)
Do not set values for a NSManagedObject
in the init
method. A NSManagedObject
gets populated after the init
is called. If you need to override values then do so in the awakeFromFetch
or awakeFromInsert
methods.
I would strongly suggest reviewing the Core Data Programming Guide on what to override.