[iOS] NSCoding μ΄λ? (feat. μΈμ½λ©, λμ½λ©, μμΉ΄μ΄λΉ)
μλ νμΈμ. μ€λμ 곡μλ¬Έμμμ μ€λͺ νλ NSCoding λ₯Ό 곡λΆν΄λ³΄κ² μ΅λλ€πΆ
NSCoding
protocol NSCoding
NSCodingμ ν΄λμ€κ° encoding κ³Ό decoding λλ κ²μ κ°λ₯νκ² ν΄μ£Όλ νλ‘ν μ½μ λλ€.
λ€μ λ§νλ©΄, NSCoding μ μ±νν ν΄λμ€λ encoding κ³Ό decoding μ΄ κ°λ₯ν΄μ§λλ€.
μΈμ½λ©μ κΈ°μ‘΄μ νμμ λ€λ₯Έ νμμΌλ‘ λ³ννλ κ²μ κ°λ¦¬ν΅λλ€.
μλ₯Ό λ€μ΄ Swift μ Struct μΈμ€ν΄μ€λ₯Ό JSON ννμ λ¬Έμμ΄λ‘ λ³νμν€λ κ²μ JSON Encoding μ΄λΌκ³ λΆλ₯Ό μ μμ΅λλ€.
λμ½λ©μ κ·Έ λ°λμ λλ€.
κ·Έλ¦¬κ³ Encoding κ³Ό Decoding μ μμΉ΄μ΄λΉ(Archiving) κ³Ό λμ€νΈλ¦¬λ·°μ (Distribution) μ νμν©λλ€.
κ°μ
νλ‘ν μ½μ μꡬμ¬νμ΄λ―λ‘, NSCoding νλ‘ν μ½μ μ΄ νλ‘ν μ½μ μ±νν ν΄λμ€κ° λ κ°μ§ λ©€λ²λ₯Ό ꡬνν κ²μ μꡬν©λλ€.
Encoding κ³Ό Decoding μ μμΉ΄μ΄λΉ(Archiving) κ³Ό λμ€νΈλ¦¬λ·°μ (Distribution)μ κΈ°λ³Έ 쑰건μ λλ€.
μ¬κΈ°μ μμΉ΄μ΄λΉ(Archiving)μ μ€λΈμ νΈλ μ΄λ€ ꡬ쑰μ λ°μ΄ν°κ° λμ€ν¬μ μ μ₯λλ κ²μ μλ―Έν©λλ€.
π‘ μ’ λ μμΈν, Archivesλ?
μ€λΈμ νΈμ κ°μ μν€ν μ²μ μ’ μλμ§ μλ λ°μ΄νΈμ μ΄λ€( stream of bytes) λ‘ λ³νν μ μλ μλ¨μ μ 곡ν©λλ€.
κ·Έλ¦¬κ³ μμΉ΄μ΄λΉμ νλ 주체λ μμΉ΄μ΄λ²(Archiver) μ λλ€. NSKeyedArchiver λ±μ μ¬μ©ν©λλ€.
μ΄ λ μ΄ λ°μ΄νΈ μ΄μ μ€λΈμ νΈμ κ°λ€ μ¬μ΄μ κ΄κ³μ identiy λ μ μ§ν μνλ‘ λ³νλμ΄μΌ ν©λλ€.
Cocoa archives can hold Objective-C objects, scalars, arrays, structures, and strings
μΆμ² : Archives and Serializations Programming Guide
κ·Έλ¦¬κ³ λμ€νΈλ¦¬λ·°μ (Distribution)μ μ€λΈμ νΈκ° μ μ λ κ³³ λ°μ λ€λ₯Έ μ£Όμ 곡κ°μ 볡μ¬λλ κ²μ μλ―Έν©λλ€.
μμΉ΄μ΄λΉλ λ°μ΄λ리 λ°μ΄ν°λ₯Ό λΆλ¬μμ λ€λ₯Έ κ³³μμ λμ½λ©νμ¬ μ¬μ©ν μ μμΌλ μ΄λ° μλ―Έλ‘ μ΄ κ²μΌλ‘ μ΄ν΄νλ€.
NSCoding νλ‘ν μ½μ μ±ννκ² λλ©΄ NSCoder νμ μ coder κ° μ€λΈμ νΈμ λ©μλ encode(with:) μ init(coder:) λ₯Ό νΈμΆν©λλ€.
encode(with:) λ μ€λΈμ νΈκ° μμ μκ² μ 곡λ°μ coder λ₯Ό ν΅ν΄ μΈμ€ν΄μ€ λ³μλ₯Ό μΈμ½λ©νλλ‘ μ§μν©λλ€.
κ·Έλ¦¬κ³ μ€λΈμ νΈλ μ΄ λ©μλλ₯Ό μμ°¨λ‘ μ λ¬λ°μ μ μμ΅λλ€.
βοΈ"AλΌλ μ€λΈμ νΈμκ² λ©μμ§λ₯Ό μ λ¬νλ€" = "Aμ λ©μλλ₯Ό νΈμΆνλ€" μ΄λ―λ‘, μ λ¬Έμ₯μ encode(with:) λ©μλκ° μ¬λ¬λ² νΈμΆλλ€λ μλ―Έμ λλ€.
init(coder:) λ μ λ¬λ°μ coder μ λ€μ΄μλ data (λ°μ΄λ리 λ°μ΄ν°) λ₯Ό μ΄μ©νμ¬ ν΄λΉ μ€λΈμ νΈ νμμΌλ‘ μ΄κΈ°ννλλ‘ μ§μν©λλ€.
κ·Έκ²μ λ€λ₯Έ μμ±μλ₯Ό λ체νκ³ , νλμ μ€λΈμ νΈλΉ νλ²λ§ 보λ΄μ§λλ€.
μ΄λ€ μ€λΈμ νΈ ν΄λμ€κ° codeable ( encoding κ³Ό decodingμ΄ κ°λ₯ν) νλ €λ©΄ λ°λμ NSCoding νλ‘ν μ½λ₯Ό μ±ννμ¬ κ·Έ μꡬμ¬νμ ꡬνν΄μΌν©λλ€. (μ¬κΈ°μ Codable νλ‘ν μ½μ μμ§ μκ°νμ§ μλ κ²μΌλ‘ ^^)
macOS 10.2 μ΄ν λΆν°λ KeyedArchiving μ μ£Όλ‘ μ¬μ©νλ€κ³ ν©λλ€.
Keyed archives λ NSKeyedArchiver μ NSKeyedUnarchiver λ₯Ό μ¬μ©νμ¬ μμ±λ©λλ€.
μ 리
κ°μ²΄λ₯Ό μμΉ΄μ΄λΉ νκ³ μΆλ€λ©΄ (νμΌλ‘ μ μ₯νκ³ μΆλ€λ©΄) NSObjcet λ₯Ό μμνκ³ , NSCoding νλ‘ν μ½μ ꡬννλ©΄ λ©λλ€.
νμ§λ§ ꡬ쑰체λ μμΉ΄μ΄λΉ ν μ μμ΅λλ€. ꡬ쑰체μ κ²½μ° Encodable κ³Ό Decodable νλ‘ν μ½μ μ΄μ©ν©λλ€.
μμ§ μ΄ν΄κ° νμν λΆλΆ π€
archivedData(withRootObject:requiringSecureCoding:)
NSKeyedArchiver μ νμ λ©μλμΈλ°, 'root of the object graph to archive' λΌλ ννμ΄ μ΄ν΄κ° κ°μ§ μλλ€.
μμΉ΄μ΄λΉ λμμ ν΄λμ€κ° μ΄λ€ ν΄λμ€μ μλΈ ν΄λμ€μ΄λ©΄, κ·Έ ν΄λμ€ κ³μΈ΅μ λ£¨νΈ ν΄λμ€λ₯Ό μ λ¬νλΌλ μλ―Έ μΈκ±΄κ°?
λ!
π€π’[μ°μ§±μ iOS λΈλ‘κ·Έ]π΅π»
iOSλ₯Ό 곡λΆνλ©΄μ λ°°μ΄ λ΄μ©μ κΈ°λ‘νκ³ μμ΅λλ€.
μ°Έκ³ μλ£ 1: https://developer.apple.com/documentation/foundation/nscoding