상세 컨텐츠

본문 제목

Guide To Swift Codable. Chapter 5: Building an In-Flight Service App with User Defaults

TIL/Swift Codable

by box-jeon 2018. 5. 16. 08:11

본문

챕터 제목에 User Defaults가 나오지만 메인은 Property List를 encode/decode 하는 방법입니다. 


Property List (.plist)

Apple ecosystem에서 사용되는 XML 포맷의 파일입니다. 지원하는 데이터 타입은 다음과 같습니다. JSON과 달리 integer와 floating-point를 구분해서 제공하고 date와 data를 지원하기 때문에, PropertyListDecoder는 decodingStrategy 같은 것이 필요치 않습니다.

  • array: <array>
  • dictionary: <dict> (with <key>)
  • string: <string>
  • integer: <integer>
  • floating-point: <real>
  • binary data: <data>
  • date: <date>
  • boolean: <true/> or <false/>


PropertyListDecoder

승무원이 기내에서 사용할 주문내역 저장 앱을 가정하고 있는데, 3만 피트 상공에서는 인터넷 접속 상태가 고르지 못하기 때문에 모든 데이터를 로컬에 저장하려고 합니다. PropertyListDecoder를 이용해 bundle에 저장된 plist file을 읽어들입니다.


UserDefaults

깊은 생각 없이 프로젝트 전반에 걸쳐 마구 사용중인 UserDefaults입니다. iCloud에 올라가는 문제도 그렇고, 문서를 확인해 개념을 명확히 할 필요가 있습니다. UserDefaults.register()를 통해, 기본값을 설정하는 것도 가능합니다. 저는 보통 UserDefaults에서 값을 꺼낼 때 ??를 사용합니다.

  • Key-Value Store: Dictionary처럼 사용할 수 있습니다.
  • Persistent: 앱 종료 후에도 값이 유지됩니다.
  • Interprocess: The user defaults database is shared across all apps running on the system. You can choose to set values that can be read globally or by certain apps. (네?!?!?!?!?!)
  • Hierarchicial: When looking up the value for a key, a search list is consulted until match is found. Values set higher up in the search path trump other values.
  • Optimized for Storing User Settings: Works best when the data is small, and if data is read frequently, and written only occasionally.


관련글 더보기

댓글 영역