ios: Implement KvPrefs using NSUserDefaults
This commit is contained in:
77
shared/src/iosMain/kotlin/app/klottr/prefs/KvPrefs.kt
Normal file
77
shared/src/iosMain/kotlin/app/klottr/prefs/KvPrefs.kt
Normal file
@@ -0,0 +1,77 @@
|
||||
package app.klottr.prefs
|
||||
|
||||
import platform.Foundation.NSBundle
|
||||
import platform.Foundation.NSUserDefaults
|
||||
|
||||
actual object KvPrefs {
|
||||
private val d: NSUserDefaults by lazy { NSUserDefaults.standardUserDefaults() }
|
||||
private val listeners = mutableSetOf<(String?) -> Unit>()
|
||||
|
||||
actual fun init(platformArg: Any?) {
|
||||
// iOS needs no arg; kept for parity with Android.
|
||||
}
|
||||
|
||||
actual fun getString(key: String, def: String?): String? =
|
||||
d.stringForKey(key) ?: def
|
||||
|
||||
actual fun putString(key: String, value: String?) {
|
||||
if (value == null) d.removeObjectForKey(key)
|
||||
else d.setObject(value, forKey = key)
|
||||
notifyChanged(key)
|
||||
}
|
||||
|
||||
actual fun getInt(key: String, def: Int): Int =
|
||||
if (d.objectForKey(key) == null) def else d.integerForKey(key).toInt()
|
||||
|
||||
actual fun putInt(key: String, value: Int) {
|
||||
d.setInteger(value.toLong(), forKey = key)
|
||||
notifyChanged(key)
|
||||
}
|
||||
|
||||
actual fun getBoolean(key: String, def: Boolean): Boolean =
|
||||
if (d.objectForKey(key) == null) def else d.boolForKey(key)
|
||||
|
||||
actual fun putBoolean(key: String, value: Boolean) {
|
||||
d.setBool(value, forKey = key)
|
||||
notifyChanged(key)
|
||||
}
|
||||
|
||||
actual fun getStringSet(key: String): Set<String> {
|
||||
// Stored as NSArray<String> in defaults
|
||||
val arr = d.arrayForKey(key) as? List<*>
|
||||
return arr?.mapNotNull { it as? String }?.toSet() ?: emptySet()
|
||||
}
|
||||
|
||||
actual fun putStringSet(key: String, value: Set<String>) {
|
||||
d.setObject(value.toList(), forKey = key)
|
||||
notifyChanged(key)
|
||||
}
|
||||
|
||||
actual fun remove(key: String) {
|
||||
d.removeObjectForKey(key)
|
||||
notifyChanged(key)
|
||||
}
|
||||
|
||||
actual fun clearAll() {
|
||||
// Clear this app's domain
|
||||
val domain = NSBundle.mainBundle.bundleIdentifier
|
||||
if (domain != null) {
|
||||
d.removePersistentDomainForName(domain)
|
||||
notifyChanged(null)
|
||||
}
|
||||
}
|
||||
|
||||
actual fun addListener(listener: (key: String?) -> Unit) {
|
||||
listeners.add(listener)
|
||||
}
|
||||
|
||||
actual fun removeListener(listener: (key: String?) -> Unit) {
|
||||
listeners.remove(listener)
|
||||
}
|
||||
|
||||
private fun notifyChanged(key: String?) {
|
||||
// Snapshot to avoid concurrent modification if listeners add/remove inside callback
|
||||
val snapshot = listeners.toList()
|
||||
snapshot.forEach { it.invoke(key) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user