Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created May 30, 2016 02:18
Show Gist options
  • Save ukitaka/be95abb25b0fb6c92b49722d9d059b6c to your computer and use it in GitHub Desktop.
Save ukitaka/be95abb25b0fb6c92b49722d9d059b6c to your computer and use it in GitHub Desktop.
Realmのインスタンス生成
import RealmSwift
private let RealmSchemaVersion: UInt64 = 1
private let DefaultInMemoryRealmIndentifier = "..............."
private func realmfileURL(fileName: String, bundleIdentifier: String) -> NSURL? {
#if os(tvOS)
let path: NSString? = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first
#elseif os(iOS)
let path: NSString? = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
#else
let path: NSString? = "" //TODO
#endif
return (path?.stringByAppendingPathComponent(fileName)).flatMap(NSURL.init)
}
struct RealmInstanceManager {
static let sharedManager = RealmInstanceManager()
private let realmPath = realmfileURL("base.realm", bundleIdentifier: NSBundle.mainBundle().bundleIdentifier!)
#if DEBUG
private let defaultMainThreadInMemoryRealm: Realm
#endif
private init() {
#if DEBUG
guard let defaultMainThreadInMemoryRealm = try? Realm(configuration: defaultRealmConfiguration(true)) else {
preconditionFailure("norealm")
}
self.defaultMainThreadInMemoryRealm = defaultMainThreadInMemoryRealm
#endif
}
private func defaultRealmConfiguration(inMemory: Bool = false) -> Realm.Configuration {
return Realm.Configuration(
fileURL: inMemory ? nil : realmPath,
inMemoryIdentifier: inMemory ? DefaultInMemoryRealmIndentifier : nil,
encryptionKey: nil,
readOnly: false,
schemaVersion: RealmSchemaVersion,
migrationBlock: nil,
deleteRealmIfMigrationNeeded: false,
objectTypes: nil
)
}
func realm() -> Realm {
#if DEBUG
if let realm = DefaultMainThreadInMemoryRealm where NSThread.isMainThread() {
return realm
} else if let realm = try? Realm(configuration: defaultRealmConfiguration(true)) {
return realm
}
#else
guard let realm = try? Realm(configuration: defaultRealmConfiguration(false)) else {
preconditionFailure("norealm")
}
return realm
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment