LoginSignup
20
19

More than 5 years have passed since last update.

[swift] ファイルの保存と読み込み

Last updated at Posted at 2015-02-22

viewにbuttonを2つ設置して、それぞれ「responceToArchiveButton」と「responceUnarchiveButton」にします。
それぞれ、下記の内容を記述

kobito.swift
import UIKit

class ViewController: UIViewController {
    @IBAction func responceToArchiveButton(sender: AnyObject) {

        //パスの取得
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as Array<String>

        //保存するファイルの名前
        let filePath = String(paths[0]) + "data.txt"

        //保存するデータ
        let array = [
            "「まさか、|後罪《クライム》の|触媒《カタリスト》を〈|讃来歌《オラトリオ》〉無しで?」",
            "教師たちの狼狽した声が次々と上がる。",
            "……なんでだろう。何を驚いているんだろう。",
            "ただ普通に、この|触媒《カタリスト》を使って|名詠門《チャネル》を開かせただけなのに。",
            "そう言えば、何を|詠《よ》ぼう。",
            "自分の一番好きな花でいいかな。",
            "どんな宝石より素敵な、わたしの大好きな緋色の花。",
            "――『|Keinez《赤》』――",
            "そして、少女の口ずさんだその後に――",
            ]
            //.componentsJoinedByString("\n")

        //アーカイブしてdata.datというファイル名で保存する
        let successful = NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
        if successful{
            println("成功")
        }
    }
    @IBAction func responceUnarchiveButton(sender: AnyObject) {
        println("Unarchiveボタン押下")

        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
        .UserDomainMask, true) as Array<String>
        let filePath = String(paths[0]) + "data.txt"
        if let array = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? Array<String>{
            //println(array)

            for str in array{
                println(str)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

『iphone/ipadアプリケーション開発の教科書』より

20
19
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
20
19