LoginSignup
35
36

More than 5 years have passed since last update.

CSVデータをRealmに登録して最初からアプリに入れておく方法

Posted at

はじめに

「Objective-CでRealmを使ってハマったこと」で書こうと思ってましたが、
Swift2.0の勉強がてらこっちのテーマにしました。ハマったことは別記事で書く予定。

環境

  • OS X 10.11.1
  • Xcode 7.2
  • Swift 2.0
  • Realm 0.96.3

用途とか

変更しないマスターデータ、設定をRealmに登録しておき
あらかじめアプリに入れておきたい時などに。

CSVデータ準備

読み込むCSVデータ

TestData.csv
1,データ1
2,データ2
3,データ3

CSV読み込み、Realmにデータ登録

TestData.swift
import UIKit
import RealmSwift

class TestData: Object {
    dynamic var id = 0
    dynamic var name = ""
}
if let csvPath = NSBundle.mainBundle().pathForResource("TestData", ofType: "csv") {
    var csvString=""
    do{
        csvString = try NSString(contentsOfFile: csvPath, encoding: NSUTF8StringEncoding) as String
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    csvString.enumerateLines { (line, stop) -> () in

         // 保存先のパスを出力しておく
        print(Realm.Configuration.defaultConfiguration.path!)

        let testData = TestData()
        testData.id = Int(line.componentsSeparatedByString(",")[0])!
        testData.name = line.componentsSeparatedByString(",")[1]

        let realm = try! Realm()
        try! realm.write {
            realm.add(testData)
        }
    }
}

保存先のパスにdefault.realmファイルが生成されるので
名前を変更して(TestData.realm)プロジェクトにインポートします。

Realmからデータ取得

// .realmファイルを指定する
let config = Realm.Configuration(
    path: NSBundle.mainBundle().pathForResource("TestData", ofType:"realm"),
    readOnly: true)

let realm = try! Realm(configuration: config)
let results = realm.objects(TestData).filter("id > 2")

最後に

.realmファイルをインポートするために、シミュレーターで実行してMac上にファイルを生成する必要があります。
もっといい方法あるかもですが、こんな感じで。

参考

35
36
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
36