LoginSignup
35
28

More than 5 years have passed since last update.

[Swift4] プロパティリスト(.plist)の読み書きまとめ

Last updated at Posted at 2017-10-18

はじめに

プロパティリスト(設定ファイル)の読込と書込について色々とハマったので、簡単な例を挙げてまとめた。
なお、nilチェックは省略しています。

.plistをどこに作成するか

用途 作成場所 備考
A 読取専用 プロジェクト内 *1 書込は不可
B 読取&書込 Documents または Library *2 XcodeからGUIで見られない

*1 ViewController.swiftやinfo.plistと同じディレクトリ
*2 ディレクトリ構造についてはこちらが参考になります

A 読取専用

1)  info.plistと同じディレクトリに、sample.plistを作る (XcodeのGUIから)
2)  swiftで読み込む


let filePath = Bundle.main.path(forResource: "sample", ofType:"plist" )
let plist = NSDictionary(contentsOfFile: filePath!)

B 読取&書込

例えば、Documents配下に.plistを作って読み書きする

1)  Documents配下にsample.plistを作る


//登録したいデータ
//NSDictionaryとして作る。 keyは必ずString。
let putData: NSDictionary = ["Name": "ジャイソン・ステイサム", "Age": 50, "isPowerful": true]

//書き込む
let manager = FileManager.default
let documentDir = manager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = documentDir.appendingPathComponent("sample.plist")
putData.write(to:url, atomically: true)

2)  読み込む


//NSDictionaryとして読み込む
let manager = FileManager.default
let documentDir = manager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = documentDir.appendingPathComponent("sample.plist")
let plist = NSDictionary(contentsOfFile: url.path)

//値を抜き出して使う
print("名前: ", plist!["Name"])
print("年齢: ", plist!["Age"])
print("強いかどうか: ", plist!["isPowerful"])

参考

公式 About Property Lists
iOSでデータを永続化する方法
Swiftでプロジェクト内のplistを読み込む方法
plistを読み込む

35
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
28