이번에 프로젝트에 UserDefaults를 사용하게됬는데 딱히 사용한 적이 없는 UserDefaults에 대해서 따로 알아본 내용들을 정리만 한 내용들이다.
UserDefaults는 iOS 애플리케이션에서 데이터를 영구적으로 저장하는 인터페이스다.
// Codable 프로토콜을 사용한 커스텀 객체 저장
struct UserProfile: Codable {
let name: String
let age: Int
}
// 저장
let profile = UserProfile(name: "홍길동", age: 25)
if let encoded = try? JSONEncoder().encode(profile) {
UserDefaults.standard.set(encoded, forKey: "userProfile")
}
// 읽기
if let data = UserDefaults.standard.data(forKey: "userProfile"),
let profile = try? JSONDecoder().decode(UserProfile.self, from: data) {
print(profile.name, profile.age)
}
// 키 값을 상수로 관리
struct UserDefaultsKeys {
static let userProfile = "userProfile"
static let isDarkMode = "isDarkMode"
static let lastAccessTime = "lastAccessTime"
}
저장 방식 | 사용 케이스 |
---|---|
CoreData | 복잡한 데이터 구조, 대용량 데이터 |
Keychain | 보안이 필요한 민감한 정보 |
File System | 큰 파일이나 문서 |
SQLite | 관계형 데이터베이스 필요 시 |
class OnboardingManager {
static let shared = OnboardingManager()
var hasCompletedOnboarding: Bool {
get {
UserDefaults.standard.bool(forKey: "hasCompletedOnboarding")
}
set {
UserDefaults.standard.set(newValue, forKey: "hasCompletedOnboarding")
}
}
}
class ThemeManager {
static let shared = ThemeManager()
var isDarkMode: Bool {
get {
UserDefaults.standard.bool(forKey: "isDarkMode")
}
set {
UserDefaults.standard.set(newValue, forKey: "isDarkMode")
}
}
}
// 변경 알림 수신
NotificationCenter.default.addObserver(
self,
selector: #selector(handleDefaultsChanged),
name: UserDefaults.didChangeNotification,
object: nil
)
// 명시적 동기화
UserDefaults.standard.synchronize()
class DataCleanupManager {
static func cleanupOldData() {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "outdatedKey")
// 필요한 정리 작업 수행
}
}
// 도메인별 구분
struct UserDefaultsKeys {
struct User {
static let profile = "user.profile"
static let settings = "user.settings"
}
struct App {
static let lastVersion = "app.lastVersion"
static let launchCount = "app.launchCount"
}
}
class UserDefaultsBackup {
static func backup() -> [String: Any] {
return UserDefaults.standard.dictionaryRepresentation()
}
static func restore(from backup: [String: Any]) {
for (key, value) in backup {
UserDefaults.standard.set(value, forKey: key)
}
}
}
UserDefaults는 간단한 데이터 저장에 적합한 도구라고한다.
사실 개념적인것만 정리해놓고 실사용이나 내 프로젝트에서 어떻게 적용해야되는지는 아직 이해를 못한 상황인지라 내일중으로 튜터님께 찾아뵈서 사용법과 내가 찾은 개념들이 맞는지 여쭤볼 예정이다.