NSKeyUnarchiver导致崩溃

时间:2017-01-20 18:15:09

标签: ios swift uitableview crash nskeyedarchiver

斯威夫特3,

我在我的iOS应用程序中使用NSUserDefaults来保存和加载indexPath以及动作发生的行的哪个部分。因为我在tableview中的每一行都有一个按钮。在重新加载表时再次加载,在ViewDidLoad中。

在ViewDidLoad中,我正在调用fetch函数,它应该保存并加载任何东西。

func fetchData() {

    // request from remote or local
    data = [testArray]

    // Update the items to first section has 0 elements,
    // and place all data in section 1
    items = [[], data ?? []]

    // apply ordering
    applySorting() { "\($0)" }

    // save ordering
    saveSorting() { "\($0)" }

    // refresh the table view
    myTableView.reloadData()
}

在我的buttonAction中,我正在使用saveSorting()函数。

func saveSorting(_ dataIdBlock: (Any) -> String) {

    guard let items = self.items else { return }

    for (section, rows) in items.enumerated() {
        for (row, item) in rows.enumerated() {
            let indexPath = IndexPath(row: row, section: section)
            let dataId = dataIdBlock(item)
            let ordering = DataHandling(dataId: dataId, indexPath: indexPath)
            ordering.save(defaults: indexPath.defaultsKey)
        }
    }
}

这是我的断点图片,显示日志和代码中的位置。

code screenshot

感谢您帮助修复此崩溃。在应用程序完全加载之前,应用程序甚至不会将其加载到白色屏幕中。谢谢。

这是代码

class DataHandling: NSObject, NSCoding {

var indexPath: IndexPath?
var dataId: String?

init(dataId: String, indexPath: IndexPath) {
    super.init()
    self.dataId = dataId
    self.indexPath = indexPath
}

required init(coder aDecoder: NSCoder) {

    if let dataId = aDecoder.decodeObject(forKey: "dataId") as? String {
        self.dataId = dataId
    }

    if let indexPath = aDecoder.decodeObject(forKey: "indexPath") as? IndexPath {
        self.indexPath = indexPath
    }

}

func encode(with aCoder: NSCoder) {
    aCoder.encode(dataId, forKey: "dataId")
    aCoder.encode(indexPath, forKey: "indexPath")
}

func save(defaults box: String) -> Bool {

    let defaults = UserDefaults.standard
    let savedData = NSKeyedArchiver.archivedData(withRootObject: self)
    defaults.set(savedData, forKey: box)
    return defaults.synchronize()

}

convenience init?(defaults box: String) {

    let defaults = UserDefaults.standard
    if let data = defaults.object(forKey: box) as? Data,
        let obj = NSKeyedUnarchiver.unarchiveObject(with: data) as? DataHandling,
        let dataId = obj.dataId,
        let indexPath = obj.indexPath {
        self.init(dataId: dataId, indexPath: indexPath)
    } else {
        return nil
    }

}

class func allSavedOrdering(_ maxRows: Int) -> [Int: [DataHandling]] {

    var result: [Int: [DataHandling]] = [:]
    for section in 0...1 {
        var rows: [DataHandling] = []
        for row in 0..<maxRows {
            let indexPath = IndexPath(row: row, section: section)
            if let ordering = DataHandling(defaults: indexPath.defaultsKey) {
                rows.append(ordering)
            }
            rows.sort(by: { $0.indexPath! < $1.indexPath! })
        }
        result[section] = rows
    }

    return result

 }

}

错误代码:

*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (CustomCellSwift.DataOrdering) for key (root); the class may be defined in source code or a library that is not linked'

JSON代码

func retrieveData() {

    let getDataURL = "http://ip/test.org/Get.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {

        let data: Data = try Data(contentsOf: url as URL)
        jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Looping through jsonArray
        for i in 0..<jsonArray.count {

            // Create Test Object
            let gID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as! String
            let gName: String = (jsonArray[i] as AnyObject).object(forKey: "gameName") as! String

            // Add Test Objects to Test Array
            testArray.append(Test(gameTest: tName, andTestID: tID))

        }
    }
    catch {
        print("Error: (Getting Data)")
    }

    myTableView.reloadData()
}

applySorting Code

func applySorting(_ dataIdBlock: (Any) -> String) {

    // get all saved ordering
    guard let data = self.data else { return }
    let ordering = DataHandling.allSavedOrdering(data.count)

    var result: [[Any]] = [[], []]

    for (section, ordering) in ordering {
        guard section <= 1 else { continue } // make sure the section is 0 or 1
        let rows = data.filter({ obj -> Bool in
            return ordering.index(where: { $0.dataId == .some(dataIdBlock(obj)) }) != nil
        })
        result[section] = rows
    }

    self.items = result
}

1 个答案:

答案 0 :(得分:0)

您的indexPath.defaultsKey实施错误。

我发现你已经完成了in this question扩展:

请注意以下是原始问题中缺少的代码而不是我的解决方案

extension IndexPath { 
    var defaultsKey: String { 

        return "data_ordering_\(section)_\(row)" 
    } 
}

此行return "data_ordering_\(section)_\(row)"是问题所在。你有第二个班级DataOrdering与这个密钥一起存储。但你也想保存DataHandling。然后你需要一把不同的钥匙。

您需要使用唯一密钥存储在UserDefaults中。

例如,您应将其更改为:

DataHandling(defaults: "DataHandling_"+ indexPath.defaultsKey)

<强>更新

最好在save(defaults box: String)

中添加班级名称
 defaults.set(savedData, forKey: "DataHandling_"+box)

以及convenience init?(defaults box: String)

if let data = defaults.object(forKey: "DataHandling_"+box) as? Data,

(您应该在使用的其他类(DataOrdering)中更改此部分,以使保存的键对于您保存的每个不同的类都是唯一的

<强>更新

如果您重命名了课程,那么仅重置UserDefaults就足够了。您可以从模拟器中删除应用程序,或者在模拟器中转到此菜单时从模拟器中删除所有时态数据:iOS Simulator > Reset Content and Settings。但是,如果没有再次收到错误,则不应使用当前的IndexPath.defaultsKey而不使用当前的班级名称。

注意:

您可以将数组一步保存到userdefaults。您不需要从userdefaults逐步读取每个对象。如果你保存一个数组,那么订单是固定的(在我的情况下,这是相同的顺序)。我认为您应该将代码发布到https://codereview.stackexchange.com/,以便更好地优化代码