diff --git a/shared/src/iosMain/kotlin/app/klottr/prefs/KvPrefs.kt b/shared/src/iosMain/kotlin/app/klottr/prefs/KvPrefs.kt new file mode 100644 index 0000000..3c16019 --- /dev/null +++ b/shared/src/iosMain/kotlin/app/klottr/prefs/KvPrefs.kt @@ -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 { + // Stored as NSArray in defaults + val arr = d.arrayForKey(key) as? List<*> + return arr?.mapNotNull { it as? String }?.toSet() ?: emptySet() + } + + actual fun putStringSet(key: String, value: Set) { + 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) } + } +}