LoginSignup
0
0

More than 5 years have passed since last update.

NSUserDefaults の setValue と setObject

Last updated at Posted at 2018-11-09

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

事象

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 だよと思いながら補完で失敗したので、余計に時間を使ってしまった・・・。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0