微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用简单数据在swift中写入和读取plist

我试图了解如何在plist中保存一个简单的值,一个整数.
但我在网上找到保存字典和数组的唯一解决方案,我不明白我可以改变只为整数工作它.
这是当下的代码……

var musicalChoice = 1
var musicString : String = "5"

override func viewDidLoad() {
    super.viewDidLoad()
    musicString = String(musicalChoice)}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // dispose of any resources that can be recreated.
}

func writePlist() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as Nsstring
    let path = documentsDirectory.stringByAppendingPathComponent("Preferences.plist")
    musicString.writetoFile(path,atomically: true,encoding: NSUTF8StringEncoding,error:nil )
}

func readplist() {

}

解决方法

Swift 4的更新

我创建了SwiftyPlistManager.在GiHub上查看它并按照以下视频说明操作:

YouTube Documentation

https://www.youtube.com/playlist?list=PL_csAAO9PQ8bKg79CX5PEfn886SMMDj3j

Swift 3.1的更新

let bedroomFloorKey = "bedroomFloor"
let bedroomWallKey = "bedroomWall"
var bedroomFloorID: Any = 101
var bedroomWallID: Any = 101

func loadGameData() {

  // getting path to GameData.plist
  let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask,true) as NSArray
  let documentsDirectory = paths.object(at: 0) as! Nsstring
  let path = documentsDirectory.appendingPathComponent("GameData.plist")

  let fileManager = FileManager.default

  //check if file exists
  if !fileManager.fileExists(atPath: path) {

    guard let bundlePath = Bundle.main.path(forResource: "GameData",ofType: "plist") else { return }

    do {
      try fileManager.copyItem(atPath: bundlePath,toPath: path)
    } catch let error as NSError {
      print("Unable to copy file. ERROR: \(error.localizedDescription)")
    }
  }

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

  let myDict = NSDictionary(contentsOfFile: path)

  if let dict = myDict {
    //loading values
    bedroomFloorID = dict.object(forKey: bedroomFloorKey)!
    bedroomWallID = dict.object(forKey: bedroomWallKey)!
    //...
  } else {
    print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
  }
}

func saveGameData() {

  let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,true) as NSArray
  let documentsDirectory = paths.object(at: 0) as! Nsstring
  let path = documentsDirectory.appendingPathComponent("GameData.plist")

  let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
  //saving values
  dict.setobject(bedroomFloorID,forKey: bedroomFloorKey as NScopying)
  dict.setobject(bedroomWallID,forKey: bedroomWallKey as NScopying)
  //...

  //writing to GameData.plist
  dict.write(toFile: path,atomically: false)

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

这是我用来在swift中读/写plist文件方法

let bedroomFloorKey = "bedroomFloor"
let bedroomWallKey = "bedroomWall"
var bedroomFloorID: AnyObject = 101
var bedroomWallID: AnyObject = 101

func loadGameData() {

// getting path to GameData.plist
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,true) as NSArray
let documentsDirectory = paths[0] as String
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")

let fileManager = NSFileManager.defaultManager()

//check if file exists
if(!fileManager.fileExistsAtPath(path)) {
  // If it doesn't,copy it from the default file in the Bundle
  if let bundlePath = NSBundle.mainBundle().pathForResource("GameData",ofType: "plist") {

    let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
    println("Bundle GameData.plist file is --> \(resultDictionary?.description)")

    fileManager.copyItemAtPath(bundlePath,toPath: path,error: nil)
    println("copy")
  } else {
    println("GameData.plist not found. Please,make sure it is part of the bundle.")
  }
} else {
  println("GameData.plist already exits at path.")
  // use this to delete file from documents directory
  //fileManager.removeItemAtPath(path,error: nil)
}

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

var myDict = NSDictionary(contentsOfFile: path)

if let dict = myDict {
  //loading values
  bedroomFloorID = dict.objectForKey(bedroomFloorKey)!
  bedroomWallID = dict.objectForKey(bedroomWallKey)!
  //...
} else {
  println("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
}
}

func saveGameData() {

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as Nsstring
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")

var dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setobject(bedroomFloorID,forKey: bedroomFloorKey)
dict.setobject(bedroomWallID,forKey: bedroomWallKey)
//...

//writing to GameData.plist
dict.writetoFile(path,atomically: false)

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

plist文件是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>bedroomFloor</key>
    <integer>101</integer>
    <key>bedroomWall</key>
    <integer>101</integer>
    <key>XInitializerItem</key>
    <string>DoNotEverChangeMe</string>
</dict>
</plist>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐