![](/img/trans.png)
[英]fatal error: NSArray element failed to match the Swift Array Element type
[英]Swift 2.2 - NSArray element failed to match Swift Array Element Type for cells in a TableViewController
我正在制作一個簡單的Notes應用程序,啟動該應用程序時出現錯誤“ NSArray元素無法匹配Swift Array元素類型”。 盡管還有很多其他這樣的問題,但在放置時,在tableViewController中都沒有問題
cell.textLabel!.text = noteTitles[indexPath.row].title
這是我的完整代碼和數組的類:
碼:
class TableViewController: UITableViewController {
var noteTitles:[Note] = []
// MARK: - Table view data source
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return noteTitles.count
}
override func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell",
forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = noteTitles[indexPath.row].title // Error here.
return cell
}
}
和Note
類:
class Note {
var title = ""
var content = ""
}
請幫助我,告訴我我做錯了什么,並幫助我解決。 先感謝您!
這是詢問NSCoding錯誤的圖像:
這是KeyedUnarchiver錯誤的圖片:
我的第一個猜測是您更改了Note
類,並嘗試從NSUserDefaults
加載舊類。 如果先清除NSUserDefaults
會發生什么? (通過更改您正在使用的密鑰,或添加硬編碼的removeObjectForKey()
。
NSUserDefaults的數組和字典必須具有屬性列表元素。 因此通常無法將自定義對象用於NSUserDefaults。
您必須使用NSCoding和NSKeyed(Un)Archiver從數組更改為NSData
這怎么樣?
參見此處編碼和解碼對象
// just examples
class Note: NSObject, NSCoding {
var note: String = ""
// you must overriding init?(coder: NSCoder) and func encode(with: NSCoder)
// for unarchiving from NSData
required init?(coder aDecoder: NSCoder) {
super.init()
self.note = aDecoder.decodeObjectForKey("note")// just example
}
// for archiving to NSData
func encode(coder aCoder: NSCoder) {
aCoder.encodeObject(self.note, forKey: "note")
}
}
設置便箋標題(對不起,請迅速輸入3語句。您可以使用自動補全功能找到正確的代碼)
let notesArchived = NSKeyedArchiver.archivedData(withRootObject: notes), forKey: "notes") // is NSData
// save notesArchived to NSUserDefaults
獲取筆記標題
let notesData = UserDefaults.standard.data(forKey: "notes")! // NSData
let notes = NSKeyedUnarchiver.unarchiveObject(with: notesData)
這對我來說可能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.