ios: Implement KvPrefs using NSUserDefaults

This commit is contained in:
Olof Hedman
2025-09-09 15:07:12 +02:00
parent e2900b63b5
commit 143a4666b4

View 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) }
}
}