2015-11-03 36 views
1

我寫過一段代碼,當時我正在使用swift 1.2,它的功能是加載並保存來自plist的數據。它工作正常與迅速1.2,但現在即時通訊工作在迅速2.代碼仍然加載的價值,但它並沒有保存的價值。 我在設備上運行應用程序,而不是模擬器。plist文件被寫入swift 1.2但它沒有被寫入或在swift 2.0中運行,我應該怎麼做?

你可以看到下面的代碼:

func loadGameData() { 

    let path = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")! 

    let myDict = NSDictionary(contentsOfFile: path) 

    if let dict = myDict { 

     highscore = dict.objectForKey("highscore")! 


    } else { 
     print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!") 
    } 
} 

func saveGameData() { 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
    let documentsDirectory = paths.objectAtIndex(0) as! NSString 
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist") 
    let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"] 



    dict.setObject(highscore.integerValue, forKey: "highscore") 

    //writing to GameData.plist 

    dict.writeToFile(path, atomically: true) 

    let resultDictionary = NSMutableDictionary(contentsOfFile: path) 
    print("Saved GameData.plist file is --> \(resultDictionary?.description)") 

} 

控制檯消息保存代碼後:

Saved GameData.plist file is --> Optional("{\n XInitializerItem = DoNotEverChangeMe;\n highscore = 25;\n}") 

沒有人知道一個不同的代碼與SWIFT 2的作品?這一個與以前的版本很好地工作。

TNX的幫助

+0

有什麼不對這個控制檯消息?我可以看到一切都很好。 –

+0

@AndrewVyazovoy,我沒有控制檯的問題,它顯示數據被保存,但在行動時,我從plist文件加載值,它仍然顯示舊值。 –

+1

您使用其他方式確定loadGameData和saveGameData中的路徑的原因是什麼?我猜他們可能會變得不同。 – fishinear

回答

0

問題是你是從主束,而直接寫入文檔閱讀。

讀取光路:NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")!

記錄路徑:NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray

爲了解決這個問題,改變喜歡你的讀者代碼:

func loadGameData() { 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
    let documentsDirectory = paths.objectAtIndex(0) as! NSString 
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist") 

    let myDict = NSDictionary(contentsOfFile: path) 

    if let dict = myDict { 
     highscore = dict.objectForKey("highscore")! 
    } else { 
     print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!") 
    } 
} 
+0

謝謝你隊友救了我的一天,現在工作很好。 –

+0

總是樂於提供幫助。你能否接受這個答案是爲了他人的利益? – Abhinav