有没有办法更改领域数据库中的数据类型? [英] Is there a way to change the Data Type in Realm Database?

查看:47
本文介绍了有没有办法更改领域数据库中的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,我完全弄乱了数据类型(红色圆圈).有没有办法把数据类型改成整数?

As you can see the image, I totally mess up the Data Type (The red circle). Is there a way to change the Data Type into Integer?

编辑

我想将数据类型从 String 更改为 Int,并且我有现有数据,因此我无法从新领域开始而仅更改 var 类型.

I want to change the data type from a String to an Int and I have existing data so I can't start with a fresh realm and just change the var type.

class Item: Object {
    @objc dynamic var name: String?
    @objc dynamic var itemid: String?
    @objc dynamic var cateid: String?
}

推荐答案

我可能误解了这个问题,但您似乎将现有数据存储为字符串,并且您想将所有这些转换"为 Int.

I may have misunderstand the question but you appear to have existing data stored as as a String and you want to 'convert' all of those to an Int.

您不能直接将类型更改为另一种类型,也不能更改存储的数据.如果这样做,它将被标记为错误.

You cannot directly change the type to another type and have the stored data changed as well. If you do, it will be flagged with an error.

Error!
  Migration is required due to the following errors:
- Property 'Item.itemid' has been changed from 'string' to 'int'.

您需要合并一个迁移块来转换"字符串值转换为 Int.假设我们向对象‘item_id’添加了一个新的 Int 属性,沿着这些行的一些东西会将您的字符串迁移到 int 的,并且在字符串不是有效它的情况下,它将被分配一个值 0

You need to incorporate a migration block to 'convert' the string value to an Int. Assuming we add a new Int property to our object `item_id', something along these lines will migrate your strings to int's and in the case where the string is not a valid it, it will be assigned a value of 0

Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
    if (oldSchemaVersion < 1) {
        migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
            let stringValue = oldObject!["itemid"] as! String
            newObject!["item_id"] = Int(stringValue) ?? 0
        }
    }
})

此外,一旦访问 Realm,对象模型就会写入 Realm 文件.所以很简单的事情

Also, as soon as Realm is accessed, the object models are written to the Realm file. So a simple matter of

let items = realm.object(Item.self)

即使没有写入数据,也会存储该模型.如果在该行之后,var 类型从 String 更改为 Int,则会引发迁移错误.

Will store that model even if no data was ever written. If, after that line, the var type is changed from a String to an Int, it will throw the migration error.

如果是这种情况,删除 Realm 并从头开始是一种选择,并且如上所述,迁移块.

Deleting the Realm and starting from scratch is one option if that's the case, and as mentioned above, a migration block.

如果这是从未使用过的全新模型,那么正如评论和其他答案所建议的那样,只需将字符串更改为 Int.

If this is brand new model that has never been used, then as the comments and other answer suggest, just change the String to an Int.

这篇关于有没有办法更改领域数据库中的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆