Swift:将 CoreData 获取的字典数组输出到 TableView

Swift: Outputting a CoreData fetched Array of Dictionaries to a TableView

所以我基本上想要实现的是在 TableView 中显示(不同的)类别列表。这些类别是从 CoreData 中获取的,并通过 fetchRequest.returnsDistinctResults = true 的方式按字母顺序排序和过滤。 fetch 的输出是一个字典数组:

(
        {
        category = Bread;
    },
        {
        category = Cheese;
    },
        {
        category = Vegetables;
    }
)

我在将这些类别值输出到我的 TableView 时遇到一些问题,因为 var distinctResultsfunc fetchMaterial() 之外的任何地方输出为 nil,导致: fatal error: unexpectedly found nil while unwrapping an Optional value 在代码的这一部分:

return distinctResults!.count

如何才能将 distinctResults 设置为 func fetchProduct() 中设置的正确值? (假设这是解决此问题的最佳方法)。提前一千谢谢! =)

这是我的相关代码:

import UIKit
import CoreData

class CategoryTableViewController: UITableViewController {

lazy var managedObjectContext : NSManagedObjectContext? = {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    if let managedObjectContext = appDelegate.managedObjectContext {
        return managedObjectContext
    }
    else {
        return nil
    }
}()

var distinctResults: [String]!

override func viewDidLoad() {
    super.viewDidLoad()
    fetchProduct()
}

func fetchProduct() {
    let fetchRequest = NSFetchRequest(entityName: "Product")

    // Create a sort descriptor object sorting on the "category" property of the Core Data object
    let sortDescriptor = NSSortDescriptor(key: "category", ascending: true)

    // Set the list of sort descriptor in the fest request so it includes the descriptor
    fetchRequest.sortDescriptors = [sortDescriptor]
    fetchRequest.propertiesToFetch = NSArray(object: "category")
    fetchRequest.returnsDistinctResults = true
    fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType

    var distinctResults: NSArray = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil)!

}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return distinctResults!.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as CategoryTableViewCell
    let distinctResult = distinctResults[indexPath.row]

    // Configure the cell
    cell.categoryLabel?.text = distinctResult

    return cell
}
}

您没有设置您的 ivar distinctResults。在fetchProduct中,你写

var distinctResults : NSArray = ...

由于关键字 var,您正在声明一个新变量,其范围将限于 fetchProduct 方法。一旦方法returns,变量就会被丢弃。

相反,您应该将结果分配给现有变量

self.distinctResults = ...

我认为您的代码可能还有其他问题,但这是对您关于 nil 变量的问题的回答。