微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在场景委托中的容器视图中的 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 举报,一经查实,本站将立刻删除。