KVC(5) 非对象类型

2020-01-31  本文已影响0人  yxibng

参考Representing Non-Object Values

  1. 对对象属性和非对象属性都生效
  2. 非对象属性采用NSNumberNSValue来包装
  3. 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

注意 BOOLiOS平台和 macOS平台的区别

  1. macOS 平台,

    • 历史原因,BOOL 是 signed char 类型,
    • 传递@"true",@"YES"setValue:forKey:,此时,kvc 会尝试调用charValue(BOOL 是 char 类型的)。由于NSString并没有实现这个方法,所以造成运行时错误。
    • 只能传递NSNumber类型,例如 @(1) ,@(YES)
  2. 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"];

上一篇 下一篇

猜你喜欢

热点阅读