Post

Replies

Boosts

Views

Activity

Xcode saving item does not appear in shopping list
Hi Everyone, I am trying to save an item from my grocery list. I am recieving no errors however the item does not appear in the shopping list after I click save. Any help would be greatly appreciated, thank you!! // // 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   } } // // AppDelegate.swift // Shopping List // // Created by Deepak Prasad on 1/10/22. // import UIKit protocol AddItemViewControllerDelegate {   func controller(controller: AddItemViewController, didSaveItemWithName name: String, andPrice price: Float) } class AddItemViewController: UIViewController {       @IBOutlet var nameTextField: UITextField!   @IBOutlet var priceTextField: UITextField!       var delegate: AddItemViewControllerDelegate?       // MARK: -   // MARK: View Life Cycle   override func viewDidLoad() {     super.viewDidLoad()     navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save(sender:)))   }       // MARK: -   // MARK: Actions   @IBAction func cancel(sender: UIBarButtonItem) {     dismiss(animated: true, completion: nil)   }       @objc func save(sender: UIBarButtonItem) {     if let name = nameTextField.text, let priceAsString = priceTextField.text, let price = Float(priceAsString) {       // Notify Delegate       delegate?.controller(controller: self, didSaveItemWithName: name, andPrice: price)               // Dismiss View Controller       dismiss(animated: true, completion: nil)     }   } }
0
0
416
Oct ’22
XCode runtime error unrecognized selector sent to instance
Hi all, I am recieving this runtime error, "[Shopping_List.AddItemViewController save:]: unrecognized selector sent to instance ..." any help would be greatly appreciated, thank you!! // // AppDelegate.swift // Shopping List // // Created by Deepak Prasad on 1/10/22. // import UIKit protocol AddItemViewControllerDelegate {   func controller(controller: AddItemViewController, didSaveItemWithName name: String, andPrice price: Float) } class AddItemViewController: UIViewController {       @IBOutlet var nameTextField: UITextField!   @IBOutlet var priceTextField: UITextField!       var delegate: AddItemViewControllerDelegate?       // MARK: -   // MARK: View Life Cycle   override func viewDidLoad() {     super.viewDidLoad()   }       // MARK: -   // MARK: Actions   @IBAction func cancel(sender: UIBarButtonItem) {     dismiss(animated: true, completion: nil)   }       @IBAction func save(sender: UIBarButtonItem) {     if let name = nameTextField.text, let priceAsString = priceTextField.text, let price = Float(priceAsString) {       // Notify Delegate       delegate?.controller(controller: self, didSaveItemWithName: name, andPrice: price)               // Dismiss View Controller       dismiss(animated: true, completion: nil)     }   } }
2
1
1.8k
Oct ’22
XCode Runtime Error, unrecognized selector sent to instance
Hi everyone, I am new to xcode and am getting this runtime error when I click on the add button for my application. Any help would go along away, thank you! Error: "Exception NSException * "-[Shopping_List.ListViewController addItems:]: unrecognized selector sent to instance 0x7f8fe6507b50" 0x000060000263b690" override func viewDidLoad() {     super.viewDidLoad()           // Set Title     title = "Items"           // Register Class     tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)           // Create Add Button     navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(UIPushBehavior.addItem(_:)))           // Create Edit Button     navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: Selector(("editItems:")))   } // MARK: -   // MARK: Add Item View Controller Delegate Methods   func controller(controller: AddItemViewController, didSaveItemWithName name: String, andPrice price: Float) {     // Create Item     let item = Item(name: name, price: price)           // Add Item to Items     items.append(item)           // Add Row to Table View     tableView.insertRows(at: [IndexPath(row: (items.count - 1), section: 0)], with: .none)          // Save Items     saveItems()   } // MARK: -   // MARK: Actions   func addItem(sender: UIBarButtonItem) {     performSegue(withIdentifier: "AddItemViewController", sender: self)   }       func editItems(sender: UIBarButtonItem) {     tableView.setEditing(!tableView.isEditing, animated: true)   }
4
0
1.1k
Oct ’22
XCode Caution: 'archiveRootObject(_:toFile:)' was deprecated in iOS 12.0: Use +archivedDataWithRootObject:requiringSecureCoding:error: and -writeToURL:options:error: instead
Hello, I am receiving this caution, is anyone able to fix this please? Thank you in advance!     if let filePath = pathForItems() {       NSKeyedArchiver.archiveRootObject(items, toFile: filePath)               // Post Notification       NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ShoppingListDidChangeNotification") , object: self)     }   }
1
0
780
Oct ’22
XCode error "Cannot convert value of type 'NSIndexPath' to expected element type 'Array<IndexPath>.ArrayLiteralElement' (aka 'IndexPath')"
Hi everyone I am new to XCode and I am following an online tutorial for a shopping list program. I have this error that appears twice, "Cannot convert value of type 'NSIndexPath' to expected element type 'Array.ArrayLiteralElement' (aka 'IndexPath')". The tutorial I'm following is here if you need it: https://code.tutsplus.com/tutorials/ios-from-scratch-with-swift-building-a-shopping-list-application-2--cms-25516 If anyone is able to help me out or give me some guidance that would be greatly appreciated, thank you! // MARK: -   // MARK: Add Item View Controller Delegate Methods   func controller(controller: AddItemViewController, didSaveItemWithName name: String, andPrice price: Float) {     // Create Item     let item = Item(name: name, price: price)           // Add Item to Items     items.append(item)           // Add Row to Table View     tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: (items.count - 1), inSection: 0)], withRowAnimation: .None)     // The line above is where the error occurs     // Save Items     saveItems()   }       // MARK: -   // MARK: Edit Item View Controller Delegate Methods   func controller(controller: EditItemViewController, didUpdateItem item: Item) {     // Fetch Index for Item     if let index = items.firstIndex(of:item) {       // Update Table View       tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade)      // The line above is where the error occurs     }           // Save Items     saveItems()   }
2
1
2.5k
Oct ’22
Beginner question in XCode "Cannot convert value of type 'String' to expected argument type 'NSNotification.Name?'"
Hi everyone, im new to xcode and I have been following a tutorial online on how to create a shopping list program and I have recieved some errors. Is anyone able to give me some help or guidance please. For more code and understanding here is the shopping list app guide I have been following: https://code.tutsplus.com/tutorials/ios-from-scratch-with-swift-building-a-shopping-list-application-2--cms-25516 The error I am recieving is this: "Cannot convert value of type 'String' to expected argument type 'NSNotification.Name?'" Thank you in advance! import UIKit class ShoppingListViewController: UITableViewController {       let CellIdentifier = "Cell Identifier"       var items = [Item]() {     didSet {       buildShoppingList()     }   }       var shoppingList = [Item]() {     didSet {       tableView.reloadData()     }   } override func viewDidLoad() { super.viewDidLoad()           // Set Title     title = "Shopping List"           // Load Items     loadItems()           // Register Class     tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)           // Add Observer     //I recieve the error in the line below     NSNotificationCenter.default.addObserver(self, selector: "updateShoppingList:", name: "ShoppingListDidChangeNotification", object: nil)   }
4
1
2.2k
Oct ’22
Value of type 'Any' has no subscripts
Hi! I am very new to xcode and I am working on a shopping list program that I have followed through a tutorial online. I am currently getting this error and I am unsure what I have missed. Any help is appreciated. Thanks so so much!     let ud = UserDefaults.standard           if !ud.bool(forKey: "UserDefaultsSeedItems") {       if let filePath = Bundle.main.path(forResource: "seed", ofType: "plist"), let seedItems = NSArray(contentsOfFile: filePath) {         // Items         var items = [Item]()                   // Create List of Items         for seedItem in seedItems {           if let name = seedItem["name"] as? String, let price = seedItem["price"] as? Float { //2 Errors here; "Value of type 'Any' has no subscripts"             print("\(name) - \(price)")                           // Create Item             let item = Item(name: name, price: price)                           // Add Item             items.append(item)           }         }                   print(items)                   if let itemsPath = pathForItems() {           // Write to File           if NSKeyedArchiver.archiveRootObject(items, toFile: itemsPath) {             ud.set(true, forKey: "UserDefaultsSeedItems")           }         }       }     }   }
7
1
1.5k
Oct ’22