我正在將核心數據數據庫中的對象列表加載到表視圖中。[AnyObject]?'沒有名爲'subscript'的成員
class ScheduleViewController: UITableViewController {
private var items: [AnyObject]?
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let itemCount = items?.count {
return itemCount
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DayScheduleCell", forIndexPath: indexPath) as DayScheduleCell
if let act = items[indexPath.row] as Activity {
if act.client != nil {
// ...
}
}
return cell
}
}
的數據被封閉內部檢索,因此我已聲明的items
數組作爲可選的,因爲它可能是零在第一次運行。
我得到錯誤'[AnyObject]?'沒有名爲'subscript'的成員在此行if let act = items[indexPath.row] as? Activity
。
我想不出如何解決這個問題。
感謝您的回覆。我得到一個新的錯誤**不能在'if act.client!= nil'這一行用'(@lvalue Client,NilLiteralConvertible)'**'類型的參數列表調用'!='。客戶端屬性是一個擁有「客戶端」對象的屬性。請參閱Activity的'NSManagedObject' [subclass](http://pastie.org/9584414#)。在數據模型中,在客戶端的屬性下進行檢查,但檢查爲可選。 – Isuru 2014-09-22 14:32:40
'client'不是可選的,因此它不能是'nil' - 因此你不能檢查它是否爲零。if'在概念上是多餘的,當然被認爲是編譯器的錯誤 – Antonio 2014-09-22 14:46:15
所以根據[this](http://stackoverflow.com/q/25485273/1077789)的問題,即使Core Data中的屬性被標記爲可選,它在生成的NSManagedObject類中沒有提及。你必須手動添加它。我在客戶端屬性前添加了一個'?',現在它工作正常。 – Isuru 2014-09-22 14:47:26