iOS代码适用于iOS 9但不适用于iOS 8吗?

dan*_*ess 20 ios swift

我的一个标签(在我的基于选项卡的应用程序中)适用于iOS 9,但在iOS 8上不起作用.具体来说,当尝试从plist加载数据时,我得到如下所示的错误.

我有一个"Planner"选项卡,可以将条目保存到plist中.iOS 8错误 - reason: '*** -[NSKeyedUnarchiver initForReadingWithData:]: incomprehensible archive (0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30)'

保存代码:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    plistPath = appDelegate.plistPathInDocument
    plistPath2 = appDelegate.plist2PathInDocument
    // Extract the content of the file as NSData
    let data:NSData =  NSFileManager.defaultManager().contentsAtPath(plistPath)!
    let data2:NSData = NSFileManager.defaultManager().contentsAtPath(plistPath2)!
    do{
        if(numOfViewWillAppear == 0)
        {
            if let x = NSKeyedUnarchiver.unarchiveObjectWithData(data2)
            {
                self.sortedSections = NSKeyedUnarchiver.unarchiveObjectWithData(data2) as! [String]
                self.sections = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! Dictionary
            }
            numOfViewWillAppear++
        }
    }
Run Code Online (Sandbox Code Playgroud)

和AppDelegate准备代码:

    func preparePlist()
{
    let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
    let url = NSURL(string: rootPath)
    plistPathInDocument = (url?.URLByAppendingPathComponent("planner.plist").path)!

    if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
        let plistPathInBundle = NSBundle.mainBundle().pathForResource("planner", ofType: "plist")!
        do {
            try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
            print("plist copied")
        }
        catch{
            print("error copying plist!")
        }
    }
    else{
        print("plst exists \(plistPathInDocument)")
    }

}
Run Code Online (Sandbox Code Playgroud)

我将项目保存到plist的代码:

self.sections[todoItem.dueDate] = [Assignment(name: todoItem.name, dueDate: todoItem.dueDate)]
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
plistPath = appDelegate.plistPathInDocument
do{
  let sectionsData = NSKeyedArchiver.archivedDataWithRootObject(sections)
  sectionsData.writeToFile(plistPath, atomically: true)
}
Run Code Online (Sandbox Code Playgroud)

小智 1

我不确定这会有帮助,但值得一试:

self.sections = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! Dictionary
Run Code Online (Sandbox Code Playgroud)

在上述行的“保存代码”中,尝试使用NSDictionary而不是Dictionary在iOS8上运行时。我想我在某处读过,他们Dictionary最近才介绍课程。我对此并不确定,而且我在 iOS 方面是个新手,但值得一试……它可能会起作用。如果有效,只需将Dictionary线路置于if #available(ios 9.0 *)条件状态即可。