Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func getContext () -> NSManagedObjectContext {
- let appDelegate = UIApplication.shared.delegate as! AppDelegate
- return appDelegate.persistentContainer.viewContext
- }
- func storeDishesInfo (itemName: String, itemPrice: String, itemType: String) {
- let context = getContext()
- //retrieve the entity that we just created
- let entity = NSEntityDescription.entity(forEntityName: "Dishes", in: context)
- let transc = NSManagedObject(entity: entity!, insertInto: context)
- //set the entity values
- transc.setValue(itemName, forKey: "itemName")
- transc.setValue(itemPrice, forKey: "itemPrice")
- transc.setValue(itemType, forKey: "itemType")
- //save the object
- do {
- try context.save()
- print("saved!")
- } catch let error as NSError {
- print("Could not save \(error), \(error.userInfo)")
- } catch {
- }
- }
- func getDishesInfo () -> String {
- var info = ""
- //create a fetch request, telling it about the entity
- let fetchRequest: NSFetchRequest<Dishes> = Dishes.fetchRequest()
- do {
- //go get the results
- let searchResults = try getContext().fetch(fetchRequest)
- //I like to check the size of the returned results!
- print ("num of results = \(searchResults.count)")
- //You need to convert to NSManagedObject to use 'for' loops
- for trans in searchResults as [NSManagedObject] {
- let itemName = trans.value(forKey: "itemName") as! String
- let itemPrice = String(trans.value(forKey: "itemPrice") as! Double)
- let itemType = trans.value(forKey: "itemType") as! String
- info = info + itemName + " " + itemPrice + ", " + itemType + "\n"
- }
- } catch {
- print("Error with request: \(error)")
- }
- return info;
- }
- func removeRecords () {
- let context = getContext()
- // delete everything in the table Dishes
- let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Dishes")
- let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
- do {
- try context.execute(deleteRequest)
- try context.save()
- } catch {
- print ("There was an error")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement