Skip to content

Instantly share code, notes, and snippets.

@isoiphone
Created March 12, 2015 00:30
Show Gist options
  • Save isoiphone/fd907d9c2e02838200f1 to your computer and use it in GitHub Desktop.
Save isoiphone/fd907d9c2e02838200f1 to your computer and use it in GitHub Desktop.
Manual thread storage, may stick with this pattern.
extension RLMRealm {
static var threadInstance: RLMRealm! {
let threadDictionary = NSThread.currentThread().threadDictionary
if let inst = threadDictionary["SharedRealmInst"] as! RLMRealm? {
return inst
} else {
let inst = defaultRealmWithErrorHandling()
threadDictionary["SharedRealmInst"] = inst
return inst
}
}
static var secureRealmPath: String {
return RLMRealm.defaultRealmPath().stringByDeletingLastPathComponent.stringByAppendingPathComponent("secure.realm")
}
static func defaultRealmWithErrorHandling() -> RLMRealm? {
var error: NSError?
let realmPath = RLMRealm.secureRealmPath
var realm = RLMRealm(path: realmPath, readOnly: false, error: &error)
if (error != nil) {
log.debug("realm error: \(error?.localizedDescription). Will remove local database and retry.")
NSFileManager.defaultManager().removeItemAtPath(realmPath, error: nil)
var error: NSError?
realm = RLMRealm(path: secureRealmPath, readOnly: false, error: &error)
if (error != nil) {
log.error("unable to resolve realm error. \(error?.localizedDescription)")
// TODO: analytics/log this to server
} else {
log.debug("ok")
}
}
// configure realm to use iOS file system encryption
// this is in addition to realm encryption
let attr = [NSFileProtectionKey: NSFileProtectionComplete]
var fileProtectionError: NSError?
if !NSFileManager.defaultManager().setAttributes(attr, ofItemAtPath: realmPath, error: &fileProtectionError) {
log.error("error setting \(attr) on realm db: \(fileProtectionError?.localizedDescription)")
}
return realm
}
}
@jpsim
Copy link

jpsim commented Mar 12, 2015

Realm does its own RLMRealm thread caching, so you can remove the threadInstance var and use defaultRealmWithErrorHandling() directly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment