加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Objective-C setValue:forKey在c原始类型上

发布时间:2020-12-16 03:14:45 所属栏目:百科 来源:网络整理
导读:我正在尝试用自己的大书呆子书教我自己的Objective-C,这是一本很棒的书,但某些方面让我很混淆. 本章正在谈论使用setValue:forKey函数,我理解的是在NSObject中定义的一种方法.这本书说,你可以使用这个c原语,如int或float,并给出这个例子 我有一个名为Applian
我正在尝试用自己的大书呆子书教我自己的Objective-C,这是一本很棒的书,但某些方面让我很混淆.

本章正在谈论使用setValue:forKey函数,我理解的是在NSObject中定义的一种方法.这本书说,你可以使用这个c原语,如int或float,并给出这个例子

我有一个名为Appliance的自定义类,它是一个称为电压的整数实例变量,用于存储当前设备的电压
我初始化一个叫做“

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类型强制它保持其内存地址,而实际上没有将电压声明为指针?

不好意思,本章基本上踢了我的屁股.

解决方法

对象和标量类型之间的转换由Key-Value Coding方法自动处理.从 documentation:

The default implementations of valueForKey: and setValue:forKey:
provide support for automatic object wrapping of the non-object data
types,both scalars and structs.

Once valueForKey: has determined the specific accessor method or
instance variable that is used to supply the value for the specified
key,it examines the return type or the data type. If the value to be
returned is not an object,an NSNumber or NSValue object is created
for that value and returned in its place.

Similarly,setValue:forKey: determines the data type required by the
appropriate accessor or instance variable for the specified key. If
the data type is not an object,then the value is extracted from the
passed object using the appropriate -<type>Value method.

所以在你的情况下,intValue将自动应用于传递的NSNumber对象,并将生成的整数传递给setVoltage:.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读