Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 当我将核心数据添加到表视图时,我的应用程序崩溃_Swift_Uitableview_Core Data_Swift3_Nsfetchedresultscontroller - Fatal编程技术网

Swift 当我将核心数据添加到表视图时,我的应用程序崩溃

Swift 当我将核心数据添加到表视图时,我的应用程序崩溃,swift,uitableview,core-data,swift3,nsfetchedresultscontroller,Swift,Uitableview,Core Data,Swift3,Nsfetchedresultscontroller,我在一个视图控制器中有两个表视图,它们都包含彼此不相关的不同类型的数据。出于某种原因,每当我向其中一个项目添加新数据时,应用程序都会崩溃,因为它会将新数据同时添加到两个表视图中,而不是仅添加到一个表视图中。我正在尝试将数据添加到正确的表视图中。这是我的密码 var tasks: Todo! var progress: [Millestone] = [] var milestone: Millestone! var list: [Todo] = [] var taskfetch: NSFetch

我在一个视图控制器中有两个表视图,它们都包含彼此不相关的不同类型的数据。出于某种原因,每当我向其中一个项目添加新数据时,应用程序都会崩溃,因为它会将新数据同时添加到两个表视图中,而不是仅添加到一个表视图中。我正在尝试将数据添加到正确的表视图中。这是我的密码

var tasks: Todo!
var progress: [Millestone] = []
var milestone: Millestone!
var list: [Todo] = []

var taskfetch: NSFetchedResultsController<Todo>!
var progressfetch : NSFetchedResultsController<Millestone>!


    let fetching: NSFetchRequest<Todo> = Todo.fetchRequest()
    let sorting = NSSortDescriptor(key: "dateadded", ascending: true)
   fetching.predicate = NSPredicate(format: "projectname = %@", "\(title! as String)")
    fetching.sortDescriptors = [sorting]
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
        let context = appDelegate.persistentContainer.viewContext
        taskfetch = NSFetchedResultsController(fetchRequest: fetching, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        taskfetch.delegate = self

        do {
            try taskfetch.performFetch()
            if let fetchedObjects = taskfetch.fetchedObjects {
                list = fetchedObjects
            }
        } catch {
            print(error)
        }
    }

    let lining: NSFetchRequest<Millestone> = Millestone.fetchRequest()
    let sorting2 = NSSortDescriptor(key: "dateadded", ascending: true)
    lining.predicate = NSPredicate(format: "projectname = %@", "\(title! as String)")
    lining.sortDescriptors = [sorting2]
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
        let context = appDelegate.persistentContainer.viewContext
        progressfetch = NSFetchedResultsController(fetchRequest: lining, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        progressfetch.delegate = self

        do {
            try progressfetch.performFetch()
            if let fetchedObjects = progressfetch.fetchedObjects {
                progress = fetchedObjects
            }
        } catch {
            print(error)
        }
    }
func getdata() {
    let context = (UIApplication.shared.delegate as! AppDelegate!).persistentContainer.viewContext

    do {
        print("getting")


        let tasking = try context.fetch(Todo.fetchRequest())


        let progressname = try context.fetch(Millestone.fetchRequest())
    } catch{
        print("whoopsie")
    }
}
 let oktaskaction =  UIAlertAction(title: "Add", style: .default, handler: {(action:UIAlertAction!) -> Void in

        if text.textFields?[0].text != nil, text.textFields?[0].text != "" {
           // self.taskTable.beginUpdates()
            // let song = self.songs[indexPath.row]
            //(UIApplication.shared.delegate as! AppDelegate).saveContext()
            if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
                self.tasks = Todo(context: appDelegate.persistentContainer.viewContext)
                self.tasks.taskname = text.textFields?[0].text
                self.tasks.projectname = self.title
                self.tasks.completed = false
                let formatter = DateFormatter()
                formatter.dateStyle = DateFormatter.Style.medium
                formatter.timeStyle = DateFormatter.Style.none
                self.tasks.dateadded = self.date
                appDelegate.saveContext()
            }else {
                print("nothing there")
                text.textFields?[0].placeholder = "did not enter text"
            }
            self.taskTable.refreshControl?.beginRefreshing()
            self.getdata()
            self.taskTable.reloadData()

        }

    })


    let okAction = UIAlertAction(title: "Add Milestone", style: .default, handler: {(action:UIAlertAction!) -> Void in
        if text2.textFields?[0].text != nil, text2.textFields?[0].text != "", text2.textFields?[1].text != nil {
            print("i'm working on adding the milestone")
            if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
                self.milestone = Millestone(context: appDelegate.persistentContainer.viewContext)
                self.milestone.progressname = text2.textFields?[0].text
                self.milestone.date = text2.textFields?[1].text
                self.milestone.projectname = self.title
                appDelegate.saveContext()
                    print("adding to graph")
                    self.chartLegend.append(self.milestone.progressname!)
                    self.chartData.append(self.chartData.count + 1)


                print("saved the new milestone")
            }else {
                print("nothing there")
                text.textFields?[0].placeholder = "did not enter text"
            }
            self.milestoneTableView.reloadData()
            self.projectlinechart.reloadData()

        }

    })
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    print("Begining")
    print("\(list.count)")
    print("\(progress.count)")
    taskTable.beginUpdates()
    milestoneTableView.beginUpdates()

}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
    case .insert:

        if let newIndexPath = newIndexPath {
                print("adding")

            taskTable.insertRows(at: [newIndexPath], with: .fade)
            milestoneTableView.insertRows(at: [newIndexPath], with: .fade)

        }
    case .delete:
        if let indexPath = indexPath {
            print("delete")
            taskTable.deleteRows(at: [indexPath], with: .fade)
            milestoneTableView.deleteRows(at: [indexPath], with: .fade)

        }
    case .update:
        if let indexPath = indexPath {
            print("updating")
            taskTable.reloadRows(at: [indexPath], with: .fade)
            milestoneTableView.reloadRows(at: [indexPath], with: .fade)

        }
    default:
        print("doing something else")
        taskTable.reloadData()
        milestoneTableView.reloadData()

    }

    if let fetchedObjects = controller.fetchedObjects {
        projects = fetchedObjects as! [Project]
        list = fetchedObjects as! [Todo]
        progress = fetchedObjects as! [Millestone]
    }
}
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        print("ending")
        print("\(list.count)")
        print("\(progress.count)")
        taskTable.endUpdates()
        milestoneTableView.endUpdates()



    }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView.tag == 1 {
        return list.count
    } else if tableView.tag == 2 {
        return progress.count
    } else {
        return 0
    }
       }


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellidentifier = "taskcell"

    let cell = tableView.dequeueReusableCell(withIdentifier: cellidentifier, for: indexPath) as! TaskTableViewCell
    if tableView.tag == 1 {
        let tasks = list[indexPath.row]//this is where the crash occurs
        cell.taskname.text = tasks.taskname
        cell.taskname.adjustsFontSizeToFitWidth = true
        if tasks.completed == true {
            cell.accessoryType = .checkmark
        }



   }
    } else if tableView.tag == 2 {
        if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
            let progress2 = progress[indexPath.row]
            if (progress2.progressname != nil), progress2.date != nil{
            cell.progressname.text = "\(progress2.progressname!) on \(progress2.date!)"
            cell.progressname.adjustsFontSizeToFitWidth = true
            self.chartData.append(self.chartData.count + 1)
            chartLegend.insert(cell.progressname.text!, at: indexPath.row)
            } else {
                cell.progressname.text = "No Milestones"
            }

        }

    }


    return cell
}
var任务:待办事项!
变量进度:[Millestone]=[]
里程碑:千禧石!
变量列表:[Todo]=[]
var taskfetch:NSFetchedResultsController!
var progressfetch:NSFetchedResultsController!
let fetching:NSFetchRequest=Todo.fetchRequest()
let sorting=NSSortDescriptor(键:“dateadded”,升序:true)
fetching.predicate=NSPredicate(格式:“projectname=%@”,“\(title!as String)”)
fetching.sortDescriptors=[排序]
如果让appDelegate=(UIApplication.shared.delegate为?appDelegate){
让上下文=appDelegate.persistentContainer.viewContext
taskfetch=NSFetchedResultsController(fetchRequest:fetching,managedObjectContext:context,sectionNameKeyPath:nil,cacheName:nil)
taskfetch.delegate=self
做{
尝试taskfetch.performFetch()
如果让fetchedObjects=taskfetch.fetchedObjects{
列表=获取对象
}
}抓住{
打印(错误)
}
}
let-line:NSFetchRequest=millstone.fetchRequest()
let sorting2=NSSortDescriptor(键:“dateadded”,升序:true)
lining.predicate=NSPredicate(格式:“projectname=%@”,“\(title!as String)”)
lining.sortDescriptors=[sorting2]
如果让appDelegate=(UIApplication.shared.delegate为?appDelegate){
让上下文=appDelegate.persistentContainer.viewContext
progressfetch=NSFetchedResultsController(fetchRequest:Line,managedObjectContext:context,sectionNameKeyPath:nil,cacheName:nil)
progressfetch.delegate=self
做{
尝试progressfetch.performFetch()
如果让fetchedObjects=progressfetch.fetchedObjects{
进度=获取的对象
}
}抓住{
打印(错误)
}
}
func getdata(){
让上下文=(UIApplication.shared.delegate为!AppDelegate!).persistentContainer.viewContext
做{
打印(“获取”)
让tasking=try context.fetch(Todo.fetchRequest())
让progressname=try context.fetch(Millestone.fetchRequest())
}抓住{
打印(“哇”)
}
}
让oktaskaction=UIAlertAction(标题:“添加”,样式:。默认,处理程序:{(操作:UIAlertAction!)->在中无效
如果text.textFields?[0]。text!=nil,text.textFields?[0]。text!=“”{
//self.taskTable.beginUpdate()
//让song=self.songs[indexPath.row]
//(UIApplication.shared.delegate为!AppDelegate).saveContext()
如果让appDelegate=(UIApplication.shared.delegate为?appDelegate){
self.tasks=Todo(上下文:appDelegate.persistentContainer.viewContext)
self.tasks.taskname=text.textFields?[0]。text
self.tasks.projectname=self.title
self.tasks.completed=false
let formatter=DateFormatter()
formatter.dateStyle=DateFormatter.Style.medium
formatter.timeStyle=DateFormatter.Style.none
self.tasks.dateadded=self.date
appDelegate.saveContext()
}否则{
打印(“没有任何内容”)
text.textFields?[0]。占位符=“未输入文本”
}
self.taskTable.refreshControl?.beginRefreshing()
self.getdata()
self.taskTable.reloadData()
}
})
让okAction=UIAlertAction(标题:“添加里程碑”,样式:。默认值,处理程序:{(操作:UIAlertAction!)->在中无效
如果text2.textFields?[0]。text!=nil,text2.textFields?[0]。text!=“”,text2.textFields?[1]。text!=nil{
打印(“我正在添加里程碑”)
如果让appDelegate=(UIApplication.shared.delegate为?appDelegate){
self.Millestone=Millestone(上下文:appDelegate.persistentContainer.viewContext)
self.milestone.progressname=text2.textFields?[0]。text
self.milestone.date=text2.textFields?[1]。text
self.milestone.projectname=self.title
appDelegate.saveContext()
打印(“添加到图形”)
self.chartLegend.append(self.milestone.progressname!)
self.chartData.append(self.chartData.count+1)
打印(“已保存新里程碑”)
}否则{
打印(“没有任何内容”)
text.textFields?[0]。占位符=“未输入文本”
}
self.milestoneTableView.reloadData()
self.projectlinechart.reloadData()
}
})
func controllerWillChangeContent(\ucontroller:NSFetchedResultsController){
打印(“开始”)
打印(“\(list.count)”)
打印(“\(progress.count)”)
taskTable.BeginUpdate()文件
milestoneTableView.beginUpdate()
}
func控制器(controller:NSFetchedResultsController,didChange anObject:Any,在indexPath:indexPath?处,对于类型:NSFetchedResultsChangeType,newIndexPath:indexPath?){
开关类型{
案例.插入:
如果让newindepath=newindepath{
打印(“添加”)
taskTable.insertRows(位于:[newIndexPath],带:.fade)
milestoneTableView.insertRows(位于:[newIndexPath],带:.fade)
}
案例.删除:
如果让indexPath=indexPath{
打印(“删除”)
taskTable.deleteRows(位于:[indexPath],带:.fade)
milestoneTableView.deleteRows(位于:[indexPath],带:.fade)
}
案例。更新:
如果让indexPath=indexPath{
打印(“更新”)
taskTable.reloadRows(位于:[indexPat