参考Representing Non-Object Values
- valueForKey:
- setValue:forKey:
- 对对象属性和非对象属性都生效
- 非对象属性采用
NSNumber
和NSValue
来包装 - KVC会自动在对象类型和非对象类型之间转换
NSNumber
Data type | Creation method | Accessor method |
---|---|---|
BOOL | numberWithBool: | boolValue (in iOS)</br>charValue (in macOS)* |
char | numberWithChar: | charValue |
double | numberWithDouble: | doubleValue |
float | numberWithFloat: | floatValue |
int | numberWithInt: | intValue |
long | numberWithLong: | longValue |
long long | numberWithLongLong: | longLongValue |
short | numberWithShort: | shortValue |
unsigned char | numberWithUnsignedChar: | unsignedChar |
unsigned int | numberWithUnsignedInt: | unsignedInt |
unsigned long | numberWithUnsignedLong: | unsignedLong |
unsigned long long | numberWithUnsignedLongLong: | unsignedLongLong |
unsigned short | numberWithUnsignedShort: | unsignedShort |
注意 BOOL
在 iOS
平台和 macOS
平台的区别
-
macOS 平台,
- 历史原因,BOOL 是
signed char
类型, - 传递
@"true"
,@"YES"
给setValue:forKey:
,此时,kvc 会尝试调用charValue
(BOOL 是 char 类型的)。由于NSString
并没有实现这个方法,所以造成运行时错误。 - 只能传递
NSNumber
类型,例如@(1)
,@(YES)
- 历史原因,BOOL 是
-
iOS平台
- BOOL is type defined as the native Boolean
- KVC invokes boolValue, 对NSNumber和格式化的
NSString
都生效。
NSValue
Data type | Creation method | Accessor method |
---|---|---|
NSPoint | valueWithPoint: | pointValue |
NSRange | valueWithRange: | rangeValue |
NSRect | valueWithRect: (macOS only). | rectValue |
NSSize | valueWithSize: | sizeValue |
自定义的结构体
typedef struct {
float x, y, z;
} ThreeFloats;
@interface MyClass
@property (nonatomic) ThreeFloats threeFloats;
@end
NSValue* result = [myClass valueForKey:@"threeFloats"];
ThreeFloats floats = {1., 2., 3.};
NSValue* value = [NSValue valueWithBytes:&floats objCType:@encode(ThreeFloats)];
[myClass setValue:value forKey:@"threeFloats"];
网友评论