LoginSignup
6

More than 5 years have passed since last update.

特殊データをUserDefaultsに保存する【Swift3.0】

Posted at

メモ

Ex: UIColorデータをUserDefaultsに保存・読み込み

保存

NSKeyedArchiver.archivedDataでData型にシリアライズ

  // Swift3.0

  let bgColor:Data = NSKeyedArchiver.archivedData(withRootObject: UIColor.green)
  UserDefaults.standard.set(bgColor, forKey: "bgColor")

読み込み

NSKeyedUnarchiver.unarchiveObjectで任意の型にデシリアライズ

  // Swift3.0

  if let wk = UserDefaults.standard.object(forKey: "bgColor") as? Data
      if let bgColor = NSKeyedUnarchiver.unarchiveObject(with: wk) as? UIColor {
           // 何か処理
      }
   }

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
6