๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

๊ฐœ์š”

UserDefaults๋ฅผ ์ด์šฉํ•ด์„œ ์•ฑ์ด ์ข…๋ฃŒ๋  ๋•Œ ๊ฐ์ฒด๋ฅผ ์ €์žฅํ•˜๊ณ , ์•ฑ์ด ๋‹ค์‹œ ์‹คํ–‰๋  ๋•Œ ๋งˆ์ง€๋ง‰ ์ƒํƒœ๋ฅผ ๋ณต์›ํ•˜๊ณ  ์‹ถ์—ˆ๋‹ค.

 

์–ด๋ ค์› ๋˜ ์ 

 

[ios] userDefaults๋ฅผ ์ด์šฉํ•œstructure ํƒ€์ž… Data ์ €์žฅํ•˜๊ธฐ

why? -> ํ”„๋กœ์ ํŠธ๋ฅผ ์ง„ํ–‰ํ•˜๋˜์ค‘ ๊ธฐ๋ณธ์ ์ธ user์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•ด์•ผํ•ด์„œ userDefault๋ฅผ ํ™œ์šฉํ–ˆ๋‹ค.(๊ตณ์ด coreData๋ฅผ ์ด์šฉํ•  ์ผ์ด ์—†์–ด์„œ ์‚ฌ์šฉํ•  ์ง€ ์•Š์•˜๋‹ค.)

velog.io

์ฒ˜์Œ์—๋Š” ์œ„ ๊ธ€์„ ๋ณด๊ณ  PropertyListEncoder & PropertyListDecoder ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ํ•ด๋ดค๋‹ค. ์•ˆ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ์•˜๋Š”๋ฐ, ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ณ  ๋‚˜๋‹ˆ (ํ™•์ธ์€ ์•ˆ ํ•ด๋ดค๋Š”๋ฐ) ์ €์žฅ์€ ๋์ง€๋งŒ, ์ฝ์–ด์˜ค๋Š” ๊ณผ์ •์—์„œ ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋˜ ๊ฑฐ ๊ฐ™๋‹ค.

 

ํ•ด๊ฒฐํ•œ ๋ฐฉ๋ฒ•

scene์˜ ์ƒ๋ช… ์ฃผ๊ธฐ๋ฅผ ์ด์šฉํ•ด์„œ ์ €์žฅ๊ณผ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ๋ฅผ ์ˆ˜ํ–‰ํ–ˆ๋‹ค.

  1. ์•ฑ์ด ์ข…๋ฃŒ๋  ๋•Œ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•œ๋‹ค. sceneWillResignActive(_ scene: UIScene)

     func sceneWillResignActive(_ scene: UIScene) {
         if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
             do {
                 try UserDefaults.standard.setObject(appDelegate.someObject, forKey: "someObject")
                 UserDefaults.standard.synchronize()
             } catch {
                 print(error.localizedDescription)
             }
         }
     }
  2. ์•ฑ์ด ์‹œ์ž‘๋  ๋•Œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜จ๋‹ค. sceneDidBecomeActive(_ scene: UIScene)

     func sceneDidBecomeActive(_ scene: UIScene) {
         do {
             let someObject = try UserDefaults.standard.getObject(forKey: "someObject", castTo: SomeObject.self)
             if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
                 appDelegate.someObject = someObject
                 NotificationCenter.default.post(name: Notification.Name.DidChangeSomePropertyNotification, object: nil)
             }
         } catch {
             print(error.localizedDescription)
         }
     }

    ํ™”๋ฉด์—์„œ someObject์— ์žˆ๋Š” ํ”„๋กœํผํ‹ฐ๋ฅผ ์ถœ๋ ฅํ•˜๋Š”๋ฐ, ๊ณ„์† 0์œผ๋กœ ๋œจ๊ธธ๋ž˜ ์ €์žฅ์ด ์•ˆ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ์—ˆ๋‹ค. ์ง์ ‘ ์ถœ๋ ฅํ•ด๋ณด๋‹ˆ ๊ฐ’์ด ์ œ๋Œ€๋กœ ๋œจ๊ธธ๋ž˜ UI๋ฅผ ์—…๋ฐ์ดํŠธํ•ด์ฃผ๋ฉด ๋˜๊ฒ ๋‹ค ์‹ถ์–ด์„œ NotificationCenter๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ’์ด ๋ณ€๊ฒฝ๋๋‹ค๊ณ  ๋ฐœํ–‰ํ•˜๋‹ˆ๊นŒ ์ •์ƒ์ ์œผ๋กœ ์ถœ๋ ฅ๋๋‹ค.

    โ“ sceneDidBecomeActive(_:) ๋Š” UI๋ฅผ ํ‘œ์‹œํ•˜๊ธฐ ์ „์— ์‹คํ–‰๋œ๋‹ค๊ณ  ์“ฐ์—ฌ์žˆ๋Š”๋ฐ, ์™œ UI๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด์ค˜์•ผ ๋ฐ์ดํ„ฐ๊ฐ€ ์ •์ƒ ์ถœ๋ ฅ ๋˜๋Š” ์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค.

๋‹ค๋ฅธ ๋กœ์ง์— ๋ฌธ์ œ๊ฐ€ ์žˆ์–ด์„œ ๊ทธ ๋ถ€๋ถ„์„ ๊ณ ์น˜๊ณ  ์žˆ์ง€๋งŒ, ์ผ๋‹จ ๋ฐ์ดํ„ฐ ์ €์žฅ์€ ํ•ด๊ฒฐ!

 

์ฐธ๊ณ  ์ž๋ฃŒ

 

Save custom objects into UserDefaults using Codable in Swift 5.1 (Protocol Oriented Approach)

Generic code to save custom objects into UserDefaults

medium.com

์ƒˆ๋กœ ๋ฐฐ์šด์ 

  • UserDefaults
  • NotifiactionCenter ํ™œ์šฉ
๋ฐ˜์‘ํ˜•