将数据保存到pList:`无法将类型'__NSCFDictionary'的值转换为'NSMutableArray'错误

时间:2016-02-16 08:11:48

标签: ios swift

我收到以下错误:

Could not cast value of type '__NSCFDictionary' (0x10dccdef0) to 'NSMutableArray' (0x10dccd978)

我正在使用本教程:http://sweettutos.com/2015/06/03/swift-how-to-read-and-write-into-plist-files/ 但是,当我使用保存功能时:

func saveScore() {

    // Save note to plist
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let pathForThePlistFile = appDelegate.plistPathInDocument

    // Extract the content of the file as NSData

    let data:NSData =  NSFileManager.defaultManager().contentsAtPath(pathForThePlistFile)!
    // Convert the NSData to mutable array

    do{
        let scoresArray = try NSPropertyListSerialization.propertyListWithData(data, options: NSPropertyListMutabilityOptions.MutableContainersAndLeaves, format: nil) as! NSMutableArray

        scoresArray.addObject(self.totalScoreLabel.text!)

        // Save to plist
        scoresArray.writeToFile(pathForThePlistFile, atomically: true)

    }catch{

        print("An error occurred while writing to plist")
    }

scoreArray是: var scoresArray:NSMutableArray!

对于pList路径,我按照教程中的指示在AppDelegate中使用此代码,从而创建“scores.plist”文件。

var plistPathInDocument:String = String()

func preparePlistForUse(){

    // 1
    let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]

    // 2
    plistPathInDocument = rootPath.stringByAppendingString("/scores.plist")
    if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
        let plistPathInBundle = NSBundle.mainBundle().pathForResource("scores", ofType: "plist") as String!

    // 3
do {
    try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
    }catch{
            print("Error occurred while copying file to document \(error)")
        }
    }
}

我确保得分.plist文件的根目录是“数组”,而不是字典。

我在这里看到了同样的问题:Swift. SIGABRT: cast value of type '__NSCFDictionary' to 'NSMutableArray'但是没有答案,请帮忙。

以下是我的pList的外观:

plist screenshot

0 个答案:

没有答案