티스토리 뷰
Key-Value Coding Programming Guide - Key-Value Coding Fundamentals - Accessing Object Properties
rhinoPHS 2019. 1. 31. 18:32Key-Value Coding Programming Guide - Key-Value Coding Fundamentals - Accessing Object Properties
BankAccount
object@interface BankAccount : NSObject
@property (nonatomic) NSNumber* currentBalance; // An attribute
@property (nonatomic) Person* owner; // A to-one relation
@property (nonatomic) NSArray< Transaction* >* transactions; // A to-many relation
@end
class Person: NSObject {
@objc var someValue:Int
init(someValue:Int) {
self.someValue = someValue;
}
}
let person = Person(someValue: 12)
person.value(forKey: #keyPath(Person.someValue))
struct SomeStructure {
var someValue: Int
}
let s = SomeStructure(someValue: 12)
let pathToProperty = \SomeStructure.someValue
let value = s[keyPath: pathToProperty]
- Getting Attribute Values Using Keysr
https://developer.apple.com/documentation/foundation/object_runtime/nskeyvaluecoding 여기 보시면 됩니다.
-setValue:forKey:는 해당 키에 해당하는 프로퍼티에 값을 넣습니다. 그리고 기본적으로 NSNumber와 NSValue는 unwrap합니다(스칼라값이나 구조체를 넣을 경우에는 개발자가 NSNumber, NSValue로 wrap해서 넣어야 합니다.). 키에 해당하는 프로퍼티가 없으면 setValue:forUndefiendKey: message.를 호출합니다. 이 메소드는 기본적으로 NSUndefinedKeyException을 호출합니다. 이 메서드를 오버라이드해서 원하는 동작을 할 수 도 있습니다.
- setValue:forKeyPath:
ket path에 해당하는 프로퍼티에 값을 넣습니다. 보통 객체간의 계층구조를 따라가는데, 그 과정에서 KVC를 사용하지 않는 객체가 있다면 setValue:forUndefinedKey:를 호출합니다.
- setValuesForKeysWithDictionary: 키값쌍을 dictionary로 만들어서 넣어줍니다. 기본적으로 각각의 키-값 쌍에 대해 setValue:forkey를 호출하고 필요에 따라서 NSNull 객체를 nil로 대체합니다.
- (id)tableView:(NSTableView *)tableview objectValueForTableColumn:(id)column row:(NSInteger)row
{
id result = nil;
Person *person = [self.people objectAtIndex:row];
if ([[column identifier] isEqualToString:@"name"]) {
result = [person name];
} else if ([[column identifier] isEqualToString:@"age"]) {
result = @([person age]); // Wrap age, a scalar, as an NSNumber
} else if ([[column identifier] isEqualToString:@"favoriteColor"]) {
result = [person favoriteColor];
} // And so on...
return result;
}
Listing 2-3Implementation of data source method with key-value coding
- (id)tableView:(NSTableView *)tableview objectValueForTableColumn:(id)column row:(NSInteger)row
{
return [[self.people objectAtIndex:row] valueForKey:[column identifier]];
}
if else 구문을 없애서 소스도 상당히 짧아졌습니다. 또한 컬럼이 추가 되더라도 소스 수정이 일어나지 않습니다. 물론 컬럼 식별자가 객제 모델의 property와 같아야 합니다.
'Swift & objc' 카테고리의 다른 글
Key-Value Coding Programming Guide - Key-Value Coding Fundamentals - Using Collection operators (0) | 2019.01.31 |
---|---|
Key-Value Coding Programming Guide - Key-Value Coding Fundamentals - Accessing Collection Properties (0) | 2019.01.31 |
Key-Value Coding Programming Guide - Getting Started - About Key-Value Coding (0) | 2019.01.31 |
swift fatalError (0) | 2018.07.06 |
Swift ErrorHandling (0) | 2018.03.24 |