I don't recieve the runtime error anymore, however the item does not save into the shopping list
//
// AppDelegate.swift
// Shopping List
//
// Created by Deepak Prasad on 1/10/22.
//
import UIKit
extension Notification.Name { // Declaration is only valid at file scope
public static let kShoppingChanged = Notification.Name("ShoppingListDidChangeNotification")
}
class ShoppingListViewController: UITableViewController {
let CellIdentifier = "Cell Identifier"
var items = [Item]() {
didSet {
buildShoppingList()
}
}
var shoppingList = [Item]() {
didSet {
tableView.reloadData()
}
}
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Set Title
title = "Shopping List"
// Load Items
loadItems()
// Register Class
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)
// Add Observer
NotificationCenter.default.addObserver(self, selector: #selector(updateShoppingList), name: .kShoppingChanged, object: nil) //'default' label can only appear inside a 'switch' statement
}
// MARK: -
// MARK: Table View Data Source Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return shoppingList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue Reusable Cell
let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath as IndexPath)
// Fetch Item
let item = shoppingList[indexPath.row]
// Configure Table View Cell
cell.textLabel?.text = item.name
return cell
}
// MARK: -
// MARK: Notification Handling
@objc func updateShoppingList(notification: NSNotification) {
loadItems()
}
// MARK: -
// MARK: Helper Methods
func buildShoppingList() {
shoppingList = items.filter({ (item) -> Bool in
return item.inShoppingList
})
}
private func loadItems() {
if let filePath = pathForItems(), FileManager.default.fileExists(atPath: filePath) {
if let archivedItems = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [Item] {
items = archivedItems
}
}
}
private func pathForItems() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
if let documents = paths.first, let documentsURL = NSURL(string: documents) {
return documentsURL.appendingPathComponent("items")?.path
}
return nil
}
}
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags: