본문 바로가기
#모바일 [Mobile]/iOS

[iOS] KVC (Key-Value Coding)

by cy_mos 2022. 1. 25.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
iOS 2022.01.25. 12:04 2022.02.01. 18:44 Dev.Yang

 

🛠 KVC (Key-Value Coding)

Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface. This indirect access mechanism supplements the direct access afforded by instance variables and their associated accessor methods.

 

KVC (Key-Value Coding)은 객체에 대한 프로퍼티 (Property)들을 Key 또는 KeyPath를 통하여 간접적으로 가져오는 방법입니다.

 

[야곰닷넷 - KVC와 KVO의 활용 및 목적]
예를 들어 어떤 객체의 특정 프로퍼티의 값을 가져오고 싶다고 할 때, 코드를 작성하는 시점에는 어떤 프로퍼티의 값을 가져오고 싶은지 정하지 않고 프로그램 실행 중에 원하는 프로퍼티의 값을 가져오게 설계하고 싶다면 KVC가 매우 유용할 것입니다. 

 

Key-Value Coding Programming Guide - KeyPath

 

KVC (Key-Value Coding)을 기반으로 사용되는 Cocoa Technologies 아래와 같습니다.

 

  • KVO (Key-Value Observing)
  • Cocoa bindings
  • Core Data
  • AppleScript

 

KVC (Key-Value Coding)에 대한 사용 방법은 아래의 소스코드와 같습니다.

더보기
class Person: NSObject {
    @objc dynamic var name: String
    @objc dynamic var age: Int
    @objc dynamic var job: String
}

let person = Person(name: "YCY", 25, "Developer")

/* 직접적으로 접근하는 방법 */
person.name 	// "YCY"
person.age 		// 25
person.job 		// "Developer"

person.name = "CYC"
person.age = 38
person.job = "Java Developer"

/* 간접적으로 접근하는 방법 - Key를 통하여 접근 */
person.value(forKey: "name")
person.value(forKey: "age")
person.value(forKey: "job")

person.setValue("AFA", forKey: "name")
person.setValue(12, forKey: "age")
person.setValue("Android Developer", forKey: "job")

/* 간접적으로 접근하는 방법 - Key Path를 통하여 접근 */
person[keyPath: \Person.name] 	// "YCY"
person[keyPath: \Person.age] 	// 25
person[keyPath: \Person.job] 	// "Developer"

person[keyPath: \Person.name] = "AAQ"
person[keyPath: \Person.age] = 49
person[keyPath: \Person.job] = "Swift Developer"

🚀 REFERENCE

반응형

댓글