当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我试图了解如何在plist中保存一个简单的值,一个整数. 但我在网上找到保存字典和数组的唯一解决方案,我不明白我可以改变只为整数工作它. 这是当下的代码…… var musicalChoice = 1var mu
我试图了解如何在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, .userDomainMask, 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, .UserDomainMask, 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, .UserDomainMask, 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>
网友评论