本章正在谈论使用setValue:forKey函数,我理解的是在NSObject中定义的一种方法.这本书说,你可以使用这个c原语,如int或float,并给出这个例子
我有一个名为Appliance的自定义类,它是一个称为电压的整数实例变量,用于存储当前设备的电压@H_403_5@我初始化一个叫做“
appliance *a = [[appliance alloc]init]; [a setValue:[NSNumber numberWithInt:240] forKey:@"voltage"];
然后他设置一个定制的电压设置器,并记录电压,当它被要求证明它的工作
-(void)setVoltage:int(x) { NSLog(@"setting voltage to %d",x); voltage =x; }
令我困惑的是NSNumber numberWithInt返回一个指向存储在堆上的NSNumber对象的指针是否正确?那么他如何使用%d标记来记录存储在NSNumber中的整数.我明白会记录整数,但不是传入的对象?此外,我认为由于电压被定义为一个整数,而不是一个指向某物的指针,它不能将地址保存在其内存中的对象中?或者是NSNumber类型强制它保持其内存地址,而实际上没有将电压声明为指针?
不好意思,本章基本上踢了我的屁股.
解决方法
The default implementations of
valueForKey:
andsetValue:forKey:
@H_403_5@ provide support for automatic object wrapping of the non-object data@H_403_5@ types,both scalars and structs.Once
valueForKey:
has determined the specific accessor method or@H_403_5@ instance variable that is used to supply the value for the specified@H_403_5@ key,it examines the return type or the data type. If the value to be@H_403_5@ returned is not an object,anNSNumber
orNSValue
object is created@H_403_5@ for that value and returned in its place.Similarly,
setValue:forKey:
determines the data type required by the@H_403_5@ appropriate accessor or instance variable for the specified key. If@H_403_5@ the data type is not an object,then the value is extracted from the@H_403_5@ passed object using the appropriate-<type>Value
method.