Persist DBCustomVariable
Closed this issue · 1 comments
boehlefeld commented
Is there a way to set DBCustomVariables that survive App restarts ?
dbukowski commented
Hi @boehlefeld
By default, DBCustomVariables store the values in memory. However, they provide a mechanism that informs you when the values are modified in the menu. You can use that to store those new values in a place that will survive app restart, for example in the UserDefaults. Here is an example:
let customVariableName = "Example Variable"
let customVariableValueKey = "Example Variable Value"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Define the variable. Note that the initial value depends on the value stored in the UserDefaults.
let exampleVariable = DBCustomVariable(name: customVariableName,
value: UserDefaults.standard.bool(forKey: customVariableValueKey))
// Add a callback to be informed when the value changes.
exampleVariable.addTarget(self, action: #selector(didUpdateExampleVariable(customVariable:)))
// Add the variable.
DBDebugToolkit.add(exampleVariable)
return true
}
// Callback.
@objc func didUpdateExampleVariable(customVariable: DBCustomVariable) {
let value = customVariable.value as? Bool
UserDefaults.standard.set(value ?? false, forKey: "test")
}