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

时间:2014-12-16 05:52:17

标签: 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() {

}

3 个答案:

答案 0 :(得分:7)

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>

答案 1 :(得分:2)

除了数组或字典之外,您不能拥有plist中的根对象。这是因为plist文件本质上是特殊的xml文件,因此当您尝试读取文件时,您要求索引处的键或对象处的对象,否则您无法获取数据。此外,在将数字插入plist时,必须将它们包装在NSNumber类中。要保存对象,请查看此answer

答案 2 :(得分:1)

我的变体函数用于在swift上读取和写入.plist,在设备上进行测试。

Exapmle:
var dataVersion = readPlist(“Options”,key:“dataVersion”)
writePlist(“选项”,键:“dataVersion”,数据:1.23)

功能:

public void flow_Resize(object sender, PaintEventArgs e)
           {
               FlowLayoutPanel flow = sender as FlowLayoutPanel;
               var item = listCtpMgr.FirstOrDefault(o => o.flp.Name == flow.Name);
               if (item == null)
                   return;
               addedCTP = (Microsoft.Office.Tools.CustomTaskPane)item.ctp;
               if (addedCTP == null)
                   return;
               ToolStrip _toolstrip = (ToolStrip)flow.Controls[0];
               int MaxButtonWidthforThisToolbar = 0;
               foreach (ToolStripItem toolStripItem in _toolstrip.Items)
               {
                   if ((toolStripItem.Width) > MaxButtonWidthforThisToolbar)
                   {
                       MaxButtonWidthforThisToolbar = (toolStripItem.Width);
                   }
               }
               MaxButtonWidthforThisToolbar += 10;
               if (addedCTP.DockPosition == MsoCTPDockPosition.msoCTPDockPositionLeft || addedCTP.DockPosition ==
   MsoCTPDockPosition.msoCTPDockPositionRight)
               {
                   if (addedCTP.Width < MaxButtonWidthforThisToolbar)
                       addedCTP.Width = MaxButtonWidthforThisToolbar;
               }
               else if (addedCTP.DockPosition == MsoCTPDockPosition.msoCTPDockPositionTop || addedCTP.DockPosition ==
   MsoCTPDockPosition.msoCTPDockPositionBottom)
               {
                   addedCTP.Height = 50;
               }
               else
               {
               addedCTP.Width = _toolstrip.Width + 27;
               addedCTP.Height = _toolstrip.Height + 57;
           }

       }