我需要为我的Other Realm
.
AppDelegate
我通过这种方法( )获得了我的领域路径。如果用户之前登录,我将检索用户的领域,否则我将只使用Default Realm
.
func getRealmPath() -> String {
let preferences : NSUserDefaults = NSUserDefaults()
let username = preferences.objectForKey(usernameKey) as! String?
if username != nil {
let realmName = ("\(username!).realm")
print("RealmName: \(realmName)", terminator: "")
let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
return documents.stringByAppendingPathComponent(realmName)
}else{
return Realm.Configuration.defaultConfiguration.path!
}
}
我通过这种方法(称为 inside AppDelegate:didFinishLaunchingWithOptions
)进行了迁移。
func updateRealm(){
let config = Realm.Configuration(path: getRealmPath(), schemaVersion: 2, migrationBlock: { (migration, oldSchemaVersion) -> Void in
print("oldSchemaVersion \(oldSchemaVersion)")
migration.create("RLMStringTimestamp", value: ["pKey": NSUUID().UUIDString, "value": "", "updatedAt": NSDate(), "createdAt": NSDate(), "deletedAt": Date().getInitDate(), "updatedBy" : " ", "syncedAt": NSDate() ])
if oldSchemaVersion < 2 {
//MIGRATION
let firstNameTimeStamp = RLMStringTimestamp(newValue: oldObject!["firstName"] as? String)
migration.create("RLMStringTimestamp", value: firstNameTimeStamp)
newObject!["firstName"] = firstNameTimeStamp
}
}
Realm.Configuration.defaultConfiguration = config
//EDIT 2
Realm.Configuration.defaultConfiguration.path = getRealmPath()
//EDIT 1
//<strike>let realm = try! Realm(path: getRealmPath())</strike>
//EDIT 4
print(Realm.Configuration.defaultConfiguration)
//EDIT 3
let realm = try! Realm()
}
对于我的 RLMCustomer 对象,我修改
var firstName: String = ""
为var firstName: RLMStringTimeStamp!
即使我将其更改 schemaVersion
为非常高的值,migrationBlock
也没有接到电话。谁能帮我发现我错过了什么或做错了什么?
运行应用程序后,它崩溃了bad excess, code = 257
编辑1:
错误:“试试!” 表达式意外引发错误:错误域 = io.realm 代码 = 0“提供的架构版本 0 小于上次设置的版本 1。” UserInfo=0x170660c00 {NSLocalizedDescription=提供的架构版本 0 小于上次设置的版本 1.}:文件 /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.0.59/src/swift/stdlib/public/核心/ErrorType.swift,第 50 行
它似乎正在读取错误的配置文件,我怀疑错误是由于Realm.Configuration.defaultConfiguration = config
我如何设置配置Other Realm
?
编辑2:
我让我
default realm
的 to 包含我的名称和路径other realm
编辑4:
看来配置文件是正确的。如果没有来自旧领域的客户记录,我可以毫无问题地运行该应用程序。只有在旧领域有客户记录时才会崩溃。我可以从oldObject["firstName"]
print(Realm.Configuration.defaultConfiguration)
Realm.Configuration { 路径 = /var/mobile/Containers/Data/Application/8670C084-75E7-4955-89FB-137620C9B00D/Documents/perwyl.realm; inMemoryIdentifier = (null); 加密密钥 = (null); 只读 = 0; 架构版本 = 2; 迁移块 = < NSMallocBlock : 0x170451220>; 动态 = 0; customSchema = (null); } oldSchemaVersion 0
非常感谢!!!
编辑 5:我的问题的解决方案
StringTimestamp object
如果我直接分配给 newObject,我不确定为什么它会崩溃。
let firstName = (oldObject!["firstName"] as? String)!
let firstNameTimeStamp = StringTimestamp(newValue: firstName)
let testName = migration.create("StringTimestamp",value: firstNameTimeStamp)
newObject!["firstName"] = firstNameTimeStamp //Crashes
newObject!["firstName"] = testName //works
感谢大家的指导!:)