gpt4 book ai didi

ios - fetchedResultsController 返回 nil

转载 作者:行者123 更新时间:2023-12-01 19:52:36 24 4
gpt4 key购买 nike

尝试创建简单的应用程序来显示从核心数据到 TableView 的数据。代码构建成功 - 每次加载时都会添加新条目,目前超过 20 个 - 但是在尝试构建表时它会崩溃。

这里我有 ViewController:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var habitTable: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

let habitClassName:String = String(describing: Habits.self)

let habit:Habits = NSEntityDescription.insertNewObject(forEntityName: habitClassName, into: DatabaseController.getContext()) as! Habits

habit.habitsPic = ":("
habit.positive = false
habit.theHabit = "do bad"

DatabaseController.saveContext()

let fetchRequest:NSFetchRequest<Habits> = Habits.fetchRequest()

do{
let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
print("number of results: \(searchResults.count)")

}
catch{
print("Error \(error)")
}

}

//CONSTRUCT TABLE VIEW
func numberOfSectionsInTableView(tableView: UITableView)-> Int {
return fetchedResultsController.sections!.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sections = fetchedResultsController.sections else {
fatalError("No sections in fetchedResultsController")
}
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "positiveCell", for: indexPath as IndexPath)
let habit = fetchedResultsController.object(at: indexPath as IndexPath) as! Habits

cell.textLabel?.text = habit.theHabit
cell.detailTextLabel?.text = habit.habitsPic

return cell
}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


//FOR DISPLAYING DATA IN TABLE
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!

func initializeFetchedResultsController() {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Habits")
let departmentSort = NSSortDescriptor(key: "theHabit", ascending: true)
let lastNameSort = NSSortDescriptor(key: "positive", ascending: true)
request.sortDescriptors = [departmentSort, lastNameSort]


let moc = DatabaseController.getContext()
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = (self as! NSFetchedResultsControllerDelegate)

do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
}

}

和数据库 Controller :
import Foundation
import CoreData


class DatabaseController {
private init(){

}

class func getContext() -> NSManagedObjectContext{
return DatabaseController.persistentContainer.viewContext
}


let container = NSPersistentContainer(name: "ada")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {

fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

// MARK: - Core Data Saving support

class func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}

它不会构建 TableView ,因为 fetchedResultsController 返回 nil。我认为这是“moc”变量的问题,但是什么?

编辑

错误 :
fatal error :在展开可选值时意外发现 nil

线 :
守卫让sections = fetchedResultsController.sections else {

最佳答案

您将获取的结果 Controller 声明为隐式展开的可选:

var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>!

它的初始值为 nil。

您还有一个名为 initializeFetchedResultsController 的方法。为该属性赋值,但 你永远不会调用那个方法 .在评论中你说你在这段代码中调用它:
guard let sections = fetchedResultsController.sections else {
fatalError("No sections in fetchedResultsController")
}

但该代码从未提及 initializeFetchedResultsController方法,因此它从不调用该方法。

你有一个可选变量,但你从来没有给它赋值。所以它永远不会获得值(value)。所以它是零。这不是核心数据问题,而是基本的 Swift。除非您给属性值,否则属性不会获得值,而您没有这样做。

关于ios - fetchedResultsController 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com