๐ Create / Update
UserDefaults.standard.set()
๐ Read
//String ํ์
UserDefaults.standard.string(forKey: "")
//Bool ํ์
UserDefaults.standard.bool(forKey: "")
//Int ํ์
UserDefaults.standard.integer(forKey: "")
๐ Delete
UserDefaults.standard.removeObject(forKey: "")
Int, String ๊ณผ ๊ฐ์ ์์ํ์ ์๋ Struct๋ Class ํ์ ์ ์ ์ฅํ๋ ค๋ฉด json ์ธ์ฝ๋ฉ ๊ณผ์ ์ด ํ์ํ๋ค.
๐ UserDefaults๋ฅผ ํ์ฉํ ๊ฐ๋จ ํฌ์คํธ์ ์ฑ ๋ง๋ค๊ธฐ
๐ก ํด๋ก์ ๋ฅผ ์ฌ์ฉํ ์ด๊ธฐํ
ํด๋ก์ ๋ด์์ ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ ์ค์ ํ ํ ๋ฐํํ์ฌ ๋ณ์์ ํ ๋นํ๋ ๋ฐฉ์์ด๋ค.
์ด๋ฅผ ํตํด ์ด๊ธฐํ์ ์ค์ ์ ํ ๊ณณ์์ ๊น๋ํ๊ฒ ์ฒ๋ฆฌํ ์ ์๋ค.
์ฌ๋ฌ ์์ฑ์ ์ค์ ํด์ผ ํ๋ ๊ฒฝ์ฐ ์ ์ฉํ๋ค.
import UIKit
import SnapKit
class ViewController: UIViewController {
private let label: UILabel = {
let label = UILabel()
label.text = "Postit"
label.textColor = .black
label.font = .boldSystemFont(ofSize: 30)
return label
}()
private let textView: UITextView = {
let textView = UITextView()
textView.text = UserDefaults.standard.string(forKey: "memo") //UserDefaults์์ ๊ฐ read
textView.backgroundColor = .systemGray3
textView.layer.cornerRadius = 10
textView.font = .boldSystemFont(ofSize: 24)
return textView
}()
private lazy var saveButton: UIButton = {
let button = UIButton()
button.setTitle("Save", for: .normal)
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 24)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(SaveButtonTapped), for: .touchDown)
return button
}()
private lazy var deleteButton: UIButton = {
let button = UIButton()
button.setTitle("Delete", for: .normal)
button.backgroundColor = .systemGreen
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = .boldSystemFont(ofSize: 24)
button.layer.cornerRadius = 10
button.addTarget(self, action: #selector(deleteButtonTapped), for: .touchDown)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
private func configureUI() {
[label, textView, saveButton, deleteButton].forEach{ view.addSubview($0) }
view.backgroundColor = .white
label.snp.makeConstraints {
$0.top.equalToSuperview().offset(100)
$0.centerX.equalToSuperview()
}
textView.snp.makeConstraints {
$0.top.equalTo(label.snp.bottom).offset(50)
$0.centerX.equalToSuperview()
$0.width.equalTo(300)
$0.height.equalTo(450)
}
deleteButton.snp.makeConstraints {
$0.top.equalTo(textView.snp.bottom).offset(50)
$0.leading.equalToSuperview().inset(70)
$0.width.equalTo(100)
$0.height.equalTo(50)
}
saveButton.snp.makeConstraints {
$0.top.equalTo(textView.snp.bottom).offset(50)
$0.trailing.equalToSuperview().inset(70)
$0.width.equalTo(100)
$0.height.equalTo(50)
}
}
@objc
private func SaveButtonTapped(){
//textView์ ์
๋ ฅ๋ ๋ฉ๋ชจ ์ ์ฅ
UserDefaults.standard.setValue(textView.text, forKey: "memo")
print("์ ์ฅ ์๋ฃ")
}
@objc
private func deleteButtonTapped(){
//textView์ ์ ์ฅ๋ ๋ฉ๋ชจ ์ญ์
UserDefaults.standard.removeObject(forKey: "memo")
textView.text = ""
print("์ญ์ ์๋ฃ")
}
}