Created
March 12, 2015 00:30
-
-
Save isoiphone/fd907d9c2e02838200f1 to your computer and use it in GitHub Desktop.
Manual thread storage, may stick with this pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Realm does its own
RLMRealm
thread caching, so you can remove thethreadInstance
var and usedefaultRealmWithErrorHandling()
directly.