gpt4 book ai didi

ios - 我可以删除一个 Realm 而不是进行迁移吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:33:53 25 4
gpt4 key购买 nike

我们将 Realm 用作缓存,因此我们想到了删除 Realm 并在我们对 Realm 中的任何模式进行更改时重新开始。

这是一个好的策略吗?有什么要注意的吗?

下面是一些示例代码:

class RealmHelper {
static let SCHEMA_NUMBER = 5
static let SCHEMA_NUMBER_KEY = "Neutum:RealmHelper:SCHEMA_NUMBER"

/// Realm property. This is a computed property to keep thread-safety,
static var realm: Realm = {
let defaults = UserDefaults.standard
// By default is 0
let schemaNumber = defaults.integer(forKey: SCHEMA_NUMBER_KEY)

if schemaNumber < SCHEMA_NUMBER {
RealmHelper.dangerousDeleteAllRealmData()
defaults.set(SCHEMA_NUMBER, forKey: SCHEMA_NUMBER_KEY)
}

return try! Realm()
}()

/// Should only be used in the static intializer. That is, this will cause
/// issues if there are any active instances of Realm.
///
/// See the documentation: https://realm.io/docs/swift/latest/#deleting-realm-files
static func dangerousDeleteAllRealmData() {
let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
do {
try FileManager.default.removeItem(at: realmURL)

var lockURL = realmURL
lockURL.appendPathComponent("lock")
try FileManager.default.removeItem(at: lockURL)

var logAURL = realmURL
logAURL.appendPathComponent("log_a")
try FileManager.default.removeItem(at: logAURL)

var logBURL = realmURL
logBURL.appendPathComponent("log_b")
try FileManager.default.removeItem(at: logBURL)

var noteURL = realmURL
noteURL.appendPathComponent("note")
try FileManager.default.removeItem(at: noteURL)
} catch {
// Do nothing (apparently can't even log ErrorType)
}
}
}

最佳答案

我强烈建议在您的 Realm.Configuration 中将 deleteRealmIfMigrationNeeded 设置为 true

文档:https://realm.io/docs/swift/latest/api/Classes/Realm/Configuration.html#/s:vVC10RealmSwift5Realm13Configuration28deleteRealmIfMigrationNeededSb

当我使用 Realm 作为缓存以防止迁移问题时我的扩展:

extension Realm
{
static var cacheConfig: Realm.Configuration {
let cacheDirs = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
let cacheURL = URL(fileURLWithPath: cacheDirs.first!)

return Realm.Configuration(
fileURL: cacheURL.appendingPathComponent("cache.realm"),
inMemoryIdentifier: nil,
syncConfiguration: nil,
encryptionKey: nil,
readOnly: false,
schemaVersion: 0,
migrationBlock: nil,
deleteRealmIfMigrationNeeded: true,
objectTypes: nil
)
}

static var cache: Realm {
do {
return try Realm(configuration: Realm.cacheConfig)
}
catch let error as NSError {
... handle error ...
}
}
}

当我想访问缓存时,只需使用 Realm.cache...

喜欢:Realm.cache.objects(Responses.self)

关于ios - 我可以删除一个 Realm 而不是进行迁移吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43947847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com