Skip to content

Instantly share code, notes, and snippets.

@niwatako
Created August 6, 2016 04:34
Show Gist options
  • Save niwatako/7859b097d72305fb2b40111f73b20fe4 to your computer and use it in GitHub Desktop.
Save niwatako/7859b097d72305fb2b40111f73b20fe4 to your computer and use it in GitHub Desktop.
AppDelegateでTweetオブジェクトを生成・保存・取り出ししてみる #CodePiece #realm_swift #realm_jp
import UIKit
import RealmSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Realmインスタンスを生成
let realm = try! Realm()
print(realm)
// Tweet.swiftに定義したTweetクラスのインスタンスを生成
let tweet = Tweet()
tweet.name = "test name"
tweet.text = "test text"
// 生成したTweetクラスのインスタンスをRealmに保存
try! realm.write { // これで書き込みトランザクションを開始
// トランザクションの中でaddすると保存できる
realm.add(tweet)
}
// いま保存したやつを取り出してみる
let tweets = realm.objects(Tweet.self)
// 結果は配列なのでループで中身を取り出す
for tweet in tweets {
print(tweet.name)
print(tweet.text)
print(tweet.createdAt)
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment