NSUserDefaultsを用いたデータ保存

Swift3.0
AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var myUserDafault:UserDefaults = UserDefaults()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let count:Int = myUserDafault.integer(forKey: "VisitCount") + 1
myUserDafault.set(count, forKey: "VisitCount")
return true
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.cyan
let myUserDafault:UserDefaults = UserDefaults()
let count:Int = myUserDafault.integer(forKey: "VisitCount")
let myLabel:UILabel = UILabel()
myLabel.text = "\(count)回目の訪問です"
myLabel.sizeToFit()
myLabel.center = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
self.view.addSubview(myLabel)
}
}
Swift 2.3
AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var myUserDafault:NSUserDefaults = NSUserDefaults()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let count:Int = myUserDafault.integerForKey("VisitCount") + 1
myUserDafault.setObject(count, forKey: "VisitCount")
return true
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.cyanColor()
let myUserDafault:NSUserDefaults = NSUserDefaults()
let count:Int = myUserDafault.integerForKey("VisitCount")
let myLabel:UILabel = UILabel()
myLabel.text = "\(count)回目の訪問です"
myLabel.sizeToFit()
myLabel.center = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
self.view.addSubview(myLabel)
}
}
2.3と3.0の差分
- UIColorの参照方法が変更(UIColor.grayColor()->UIColor.gray)
- CGRect,CGPointの初期化方法の変更(CGRectMake,CGPointMakeの廃止)
- NSUserDefaultsの廃止、UserDefaultに変更
Reference