我在尝试向上滚动我的表格 View 时遇到了崩溃。我的数组不是零。为什么每次我尝试向上滚动时它都会崩溃?我正在尝试显示来自 Core Data 的数据。
这是我的代码:
var product = [NSManagedObject]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return product.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellIdentifier = "CheckOutTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CheckOutTableViewCell
let item = product[indexPath.row]
** 每次我尝试向上滚动表格 View 时,它都会在这里崩溃
cell.productTitle.text = item.valueForKey("name") as! String
cell.productDescription.text = item.valueForKey("size") as! String
return cell
}
func fetch() {
let moc = DataController().managedObjectContext
let productFetch = NSFetchRequest(entityName: "Product")
do {
let fetchedResults: [NSManagedObject] = try moc.executeFetchRequest(productFetch) as! [Product]
if let results: [NSManagedObject] = fetchedResults {
product = results
print("results:\(results.count)")
}
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
产品.swift
import Foundation
import CoreData
class Product: NSManagedObject {
}
Product+CoreDataProperties.swift
import Foundation
import CoreData
extension Product {
@NSManaged var id: String?
@NSManaged var name: String?
@NSManaged var img: String?
@NSManaged var quantity: String?
@NSManaged var size: String?
@NSManaged var price: String?
@NSManaged var promo: String?
}
最佳答案
您应该在获取产品之前检查数组的大小,并使用可选绑定(bind)(if let
)检查字典中是否存在该值:
if indexPath.row < product.count {
let item = product[indexPath.row]
if let name = item.valueForKey("name") as? String {
cell.productTitle.text = name
}
if let size = item.valueForKey("size") as? String {
cell.productDescription.text = size
}
}
要编写更安全的代码,最好尽可能避免强制展开。
在这种情况下,假设您的模型有一个 Product
类,您应该将您的产品存储为 [Product]
,这样您就可以避免使用 键值
:
if indexPath.row < product.count {
let item = product[indexPath.row]
if let name = item.name as? String {
cell.productTitle.text = name
}
if let size = item.size as? String {
cell.productDescription.text = size
}
}
关于swift - 在 Swift 中向上滚动时 UITableview 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38823560/