NSUserDefaults の setValue と setObject


何回かはまったので備忘録。

事象

NSUserDefaults.setValue("String Value", forKey: "String Key")

とやると

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key String Value.'

と出てアプリがクラッシュする。

解決方法

setValue じゃなくて setObject を使う。

NSUserDefaults.setObject("String Value", forKey: "String Key")

説明

set(_:forKey:) - NSUserDefaults
https://developer.apple.com/documentation/foundation/userdefaults/1414067-set
The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects. For more information, see What is a Property List? in Property List Programming Guide.

ということなので、Stringなんかを保存したい場合はこちら。

setValue は NSUserDefaults のメソッドではなく、親クラスのNSObjectのメソッド

setValue(_:forKey:) - NSObject
https://developer.apple.com/documentation/objectivec/nsobject/1415969-setvalue

Key-Value Coding のためのメソッドなので、NSUserDefaults compatible じゃないものを突っ込もうと思うとエラーになるのでした。

言い訳

実際頭の中では setObject だよと思いながら補完で失敗したので、余計に時間を使ってしまった・・・。