Tôi nhận được thông báo lỗi "Đã tìm thấy bất ngờ nil
trong khi mở một Optional
" từ Swift, với lớp bên dưới. Lỗi này xảy ra trên dòng:Bất ngờ tìm thấy nil khi unwrapping một giá trị tùy chọn swift
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
Tôi có một lớp tế bào tùy chỉnh với 2 UILabels tagged 1 và 2, các cửa hàng được thiết lập
import UIKit
import Foundation
class dictionaryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
var objects = NSMutableArray()
var dataArray = [["firstName":"Debasis","lastName":"Das","email":"[email protected]"],["firstName":"John","lastName":"Doe","email":"[email protected]"],["firstName":"Jane","lastName":"Doe","email":"[email protected]"],["firstName":"Mary","lastName":"Jane","email":"[email protected]"]]
@IBOutlet
var tableView: UITableView!
var items: [String] = ["We", "Heart", "Swift"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count;//self.items.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
//cell.textLabel?.text = self.items[indexPath.row]
//return cell
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell", forIndexPath: indexPath) as UITableViewCell
let object = dataArray[indexPath.row] as NSDictionary
(cell.contentView.viewWithTag(1) as UILabel).text = object["firstName"] as? String
(cell.contentView.viewWithTag(2) as UILabel).text = object["lastName"] as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
Tôi nghĩ rằng vấn đề là với 'viewWithTag (_ :)', mà trả về một 'UIView '(Tùy chọn' UIView')?. Nếu nó là 'nil', thì truy cập thuộc tính' text' gây ra sự cố. Cố gắng thay đổi mã thành 'if let tag1 = cell.contentView.viewWithTag (1) thành UILabel {...}' và đặt điểm ngắt ở đó để xem điều gì xảy ra. – Romain