Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active September 3, 2016 01:47
Show Gist options
  • Save KentarouKanno/49b77dcc907e8937b8d6485799762909 to your computer and use it in GitHub Desktop.
Save KentarouKanno/49b77dcc907e8937b8d6485799762909 to your computer and use it in GitHub Desktop.
RealmSwfit

RealmSwfit

★ cocoapods

platform :ios, '8.0'
use_frameworks!

pod 'RealmSwift'

★ default.realm Info

print(Realm.Configuration.defaultConfiguration.description)

★ プライマリーキーのあるDataModel

class Person: Object {
    dynamic var id   = 0
    dynamic var name = ""

    override static func primaryKey() -> String? {
      return "id"
    }
}

★ データを保存 

// モデルを作成
let person  = Person()
person.name = "kentarou"
person.age  = 41

let realm = try! Realm()
try! realm.write {
    // データを保存
    realm.add(person)
}

// Personテーブルを全て出力
print(realm.objects(Person))

/*
Results<Person> (
	[0] Person {
		name = kentarou;
		age = 41;
	}
)
*/

// Model Person ------------

// Person model
class Person: Object {
    dynamic var name = ""
    dynamic var age = 0
}

★ データをログ出力

// Personテーブルを全て出力
print(realm.objects(Person))

/*
Results<Person> (
	[0] Person {
		name = kentarou;
		age = 41;
	},
	[1] Person {
		name = Kanno;
		age = 21;
	}
)
*/

// Indexを指定してログ出力
print(realm.objects(Person)[1])

/*
Person {
	name = Kanno;
	age = 21;
}
*/

★ Sum関数を使う

class Service: Object {
    
    dynamic var name = ""
    dynamic var cost = 0
    
    override static func indexedProperties() -> [String] {
        return ["name"]
    }
}

let realm = try! Realm()
let services = realm.objects(Service)
let sum: Int = services.sum("cost")

★ リレーションシップ(1対多)

// モデルを作成
let dog1 = Dog()
dog1.name = "dogName1"

let dog2 = Dog()
dog2.name = "dogName2"

let person  = Person()
person.name = "PersonName"
person.age  = 21

// リレーションシップを設定
person.dogs.append(dog1)
person.dogs.append(dog2)

let realm = try! Realm()
try! realm.write {
    // データを保存
    realm.add(person)
}

// Personテーブルを全て出力
print(realm.objects(Person))

/*
Results<Person> (
	[0] Person {
		name = PersonName;
		age = 21;
		dogs = RLMArray <0x135547420> (
			[0] Dog {
				name = dogName1;
			},
			[1] Dog {
				name = dogName2;
			}
		);
	}
)

*/

★ マイグレーション(1回目インストール実行)

// AppDelegate -------------

import UIKit
import RealmSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        Realm.Configuration.defaultConfiguration = Realm.Configuration(
            schemaVersion: 0,
            migrationBlock: { migration, oldSchemaVersion in

                migration.enumerate(Person.className()) { oldObject, newObject in

                    if oldSchemaVersion < 1 {
                        newObject?["lastName"] = "MyLastaName"
                    }
                }
        })
        return true
    }
}


// ViewController -------------

import UIKit
import RealmSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let realm = try! Realm()
        let person = Person()
        person.firstName = "MyFirstName"
        person.age = 20
        try! realm.write {
            realm.add(person)
        }

    // ログ出力
    print(realm.objects(Person)[0])

    }
}

// Model -------------

import RealmSwift

// v0
class Person: Object {
    dynamic var firstName = ""
    dynamic var age = 0
}

★ マイグレーション(2回目マイグレーション実行)

// 変更場所 

// AppDelegate -------------
// 0 => 1
schemaVersion: 1,


// ViewController -------------

// 以下をコメントアウト
/*
let person = Person()
person.firstName = "MyFirstName"
person.age = 20
try! realm.write {
    realm.add(person)
}
*/

// Model -------------
// lastNameを追加
// v1
class Person: Object {
    dynamic var firstName = ""
    dynamic var lastName = ""
    dynamic var age = 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment