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
だよと思いながら補完で失敗したので、余計に時間を使ってしまった・・・。
Author And Source
この問題について(NSUserDefaults の setValue と setObject), 我々は、より多くの情報をここで見つけました https://qiita.com/satorish/items/865d86fb7fab10d423fb著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .