如何在场景委托中的容器视图中的 tableViewController 中实例化对象

问题描述

我试图在应用程序的开头实例化 noteStore。问题是如何在应用程序启动时实例化 NotesTableViewController 中的 noteStore,它位于 NotesMainViewController 的容器视图中。

func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let _ = (scene as? UIWindowScene) else { return }
    
    let noteStore = NoteStore()
    let noteTableView = NotesTableViewController()
    let navController = window!.rootViewController as! UINavigationController
    //make the noteStore
    
    let notesController = navController.topViewController as! NotesMainViewController
    noteTableView.noteStore = noteStore
    
}


public override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    return noteStore.allNote.count
}

public override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCell",for: indexPath) as! NoteCell
    let note = noteStore.allNote[indexPath.row]
    cell.userInputLabel.text = note.userInput
    cell.detailTextLabel?.text = nil
    return cell
}

public override func tableView(_ tableView: UITableView,commit editingStyle: UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {
    
    if editingStyle == .delete {
        let notes = noteStore.allNote[indexPath.row]
        
        let title = "Delete \(notes.userInput ?? "")"
        let message = "Are you sure you want to delete this note?"
        
        let ac = UIAlertController(title: title,message: message,preferredStyle: .actionSheet)
        
        let cancelAction = UIAlertAction(title: "Cancel",style: .cancel,handler: nil)
        ac.addAction(cancelAction)
        
        let deleteAction = UIAlertAction(title: "Delete",style: .destructive,handler: { (action) -> Void in
            
            self.noteStore.deleteNote(notes)
            self.tableView.deleteRows(at: [indexPath],with: .automatic)
        })
        ac.addAction(deleteAction)
        
        present(ac,animated: true,completion: nil)
    }
    
}

public override func tableView(_ tableView: UITableView,moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath) {
    noteStore.moveItem(from: sourceIndexPath.row,to: destinationIndexPath.row)
    tableView.reloadData()
    
}

//MARK: Segue

public override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
    switch segue.identifier {
    case "showNote"?:
        if let row = tableView.indexPathForSelectedRow?.row {
            
            let notes = noteStore.allNote[row]
            let notesViewController = segue.destination as! NotesViewController
            notesViewController.noteObject = notes
            
        }
    case "addNewNote"?:
        
        let newNote = Note(userInput: "")
        noteStore.storeNote(newNote)
        
        if let index = noteStore.allNote.firstIndex(of: newNote) {
            let indexPath = IndexPath(row: index,section: 0)
            
            self.tableView.insertRows(at: [indexPath],with: .automatic)
            
        }
        let notesViewController = segue.destination as! NotesViewController
              
        notesViewController.noteObject = newNote
        
    case "showSettings"?:
        print("settings showed")
        
    default: preconditionFailure("Unexpected segue identifier")
    }
}

public class NoteStore {
private let realm = try! Realm()
var allNote = [Note]()

init() {
    self.fetchNotesFromDataBase()
}

// Load all the notes when the app starts
func fetchNotesFromDataBase() {
    let notes = Array(realm.objects(Note.self).sorted(byKeyPath: "orderingValue",ascending: true))
    self.allNote = notes
    
}

private func save(_ note: Note) {
    try! realm.write {
        realm.add(note)
    }
}

func deleteNote(_ note: Note) {
    try! self.realm.write {
        self.realm.delete(note)
    }
    // remove the note from allNotes
    if let index = allNote.firstIndex(of: note) {
        allNote.remove(at: index)
    }
    // update ordering value
    updateOrderingValue()
}

func storeNote(_ note: Note) {
    save(note)
    allNote.insert(note,at: 0)
    updateOrderingValue()
}


func moveItem(from fromIndex: Int,to toIndex: Int) {
    if fromIndex == toIndex {
        return
    }
    
    let originalNote = allNote[fromIndex]

    allNote.remove(at: fromIndex)
    allNote.insert(originalNote,at: toIndex)
    
    updateOrderingValue()

}

private func updateOrderingValue() {
    // for all the items in the allNotes array
    // update the orderingValue to the index in the array
    try! realm.write {
    for note in allNote {
        if let index = allNote.firstIndex(of: note) {
            note.orderingValue = index
        }
    }
 }

}

当我运行该应用程序时,我收到致命错误:在 noteStore.allNote.count 中隐式解包一个 Optional 值时意外发现 nil。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...