Hey guys, I’m going through the chapter 2 material and there was an earlier example that inserted a new object into the ManagedObjectContext and later called a save on the MangedObjectContext. However, in the following function, it creates an entity, but never calls a save on the MangedObjectContext. Am I missing something? I thought objects are saved to the data source only once an explicit save is called.
func insertSampleData() {
let fetchRequest = NSFetchRequest(entityName: "Bowtie")
fetchRequest.predicate = NSPredicate(format: "searchKey != nil")
let count = managedContext.countForFetchRequest(fetchRequest, error: nil)
if count > 0 {return }
let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")
let dataArray = NSArray(contentsOfFile: path!)!
for dict : AnyObject in dataArray {
let entity = NSEntityDescription.entityForName("Bowtie", inManagedObjectContext: managedContext)
let bowtie = Bowtie(entity: entity!, insertIntoManagedObjectContext: managedContext)
let btDict = dict as! NSDictionary
bowtie.name = btDict["name"] as? String
bowtie.searchKey = btDict["searchKey"] as? String
bowtie.rating = btDict["rating"] as? NSNumber
let tintColorDict = btDict["tintColor"] as? NSDictionary
bowtie.tintColor = colorFromDict(tintColorDict!)
let imageName = btDict["imageName"] as? String
let image = UIImage(named:imageName!)
let photoData = UIImagePNGRepresentation(image!)
bowtie.photoData = photoData
bowtie.lastWorn = btDict["lastWorn"] as? NSDate
bowtie.timesWorn = btDict["timesWorn"] as? NSNumber
bowtie.isFavorite = btDict["isFavorite"] as? NSNumber
}
}
Code that calls save:
// Save test bow tie
let bowtie = NSEntityDescription .insertNewObjectForEntityForName(“Bowtie”,
inManagedObjectContext: managedObjectContext) as! Bowtie
bowtie.name = “My bow tie”
bowtie.lastWorn = NSDate()
do {
try managedObjectContext.save()
} catch let error as NSError {
print(“Saving error: (error.localizedDescription)”)
}