美文网首页征服Swift
Realm Swift 数据库简单迁移

Realm Swift 数据库简单迁移

作者: Luyc_Han | 来源:发表于2017-10-16 09:30 被阅读24次

    Local Migrations
    注意在头文件引入import Realm

    // Inside your application(application:didFinishLaunchingWithOptions:)
    
    let config = Realm.Configuration(
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 1,
    
        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if (oldSchemaVersion < 1) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
        })
    
    // Tell Realm to use this new configuration object for the default Realm
    Realm.Configuration.defaultConfiguration = config
    
    // Now that we've told Realm how to handle the schema change, opening the file
    // will automatically perform the migration
    let realm = try! Realm()
    

    一般来说上面的迁移就可以如果想更新值可以使用下面的

    // Inside your application(application:didFinishLaunchingWithOptions:)
    
    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion < 1) {
                // The enumerateObjects(ofType:_:) method iterates
                // over every Person object stored in the Realm file
                migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in
                    // combine name fields into a single field
                    let firstName = oldObject!["firstName"] as! String
                    let lastName = oldObject!["lastName"] as! String
                    newObject!["fullName"] = "\(firstName) \(lastName)"
                }
            }
        })
    

    以上描述并不清晰在此附上官方文档以供查阅
    Realm Stwift

    相关文章

      网友评论

        本文标题:Realm Swift 数据库简单迁移

        本文链接:https://www.haomeiwen.com/subject/zwzhuxtx.html