My app has a Core Data entity (called Product) that has two attributes:
- A name of type String
- An image of type Binary Data (with "Allows External Storage" checked)
Right now since I am developing, I create a default object in my initial viewDidLoad
with hardcoded values for name and image. After the object is created, I can pass it around and use it in my app without issue.
However, if I update the name attribute to a new string value, and re-run the app, the image attribute becomes nil
(this behavior only happens after I re-run the app, or terminate and re-open it). Do you know what might be causing this behavior?
This is how I change the name value:
DataController.shared.viewContext.perform {
if mike {
product.name = "Mike"
} else {
product.name = "Bob"
}
try? DataController.shared.viewContext.save()
}
I am using a DataController class to interface with the persistent store:
class DataController {
static let shared = DataController(modelName: "my_model")
let persistentContainer: NSPersistentContainer
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
private init(modelName: String) {
persistentContainer = NSPersistentContainer(name: modelName)
}
func configureContexts() {
viewContext.automaticallyMergesChangesFromParent = true
viewContext.mergePolicy = NSMergePolicy.mergeByPropertyStoreTrump
}
}
I'm also using NSFetchedResultsController
. This is how I set it up in my viewDidLoad
:
fileprivate func setupFetchedResultsController() {
let fetchRequest:NSFetchRequest<Product> = Product.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "salesByVolume", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: DataController.shared.viewContext, sectionNameKeyPath: nil, cacheName: "products")
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("The request could not be performed: \(error.localizedDescription)")
}
}
Thank you!