Objective-C理解是KindOfClass [英] Objective-C understanding isKindOfClass

查看:191
本文介绍了Objective-C理解是KindOfClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C和XCode(4.4)的最新版本。



我有一个代码片段,我不明白为什么我能够使用一些行,let我解释:

  //为了理解目的:(NSMutableArray *)_ programStack 

id l_topItemOnStack = _programStack lastObject];
if([l_topItemOnStack isKindOfClass:[NSNumber class]])
{
return [l_topItemOnStack doubleValue];
}

我的问题:因为我的 l_topItemOnStack id 类型,我没有把它转换为 NSNumber ,我怎么能使用 [l_topItemOnStack doubleValue]



我猜想我必须先将其转换为NSNumber才能访问NSNumber方法...



我在这里缺少什么?

解决方案

Objective-C是一个动态语言,消息名称及其声明只是编译器的提示 - 实际的消息查找和发送在运行时发生。因此,即使编译器不知道你的对象响应 doubleValue 消息,它仍然能够调用

  return objc_msgSend(l_topItemOnStack,@selector(doubleValue)); 


$ b 编译器查找在包含的头文件中的任何地方声明的所有选择器,并尝试使用实际上下文来找到最佳匹配 - 这里doubleValue是一个唯一的名称 - 它只在NSNumber上声明,所以编译器 >你的对象确实是一个NSNumber。



如果你真的想要避免这种情况,可以在调用方法时强制转换对象,或者最初声明为NSNumber。 / p>

Latest version of Objective-C and XCode (4.4).

I have a code snippet and I cannot understand why I'm able to use some lines, let me explain :

// For understanding purpose : (NSMutableArray*)_programStack

id l_topItemOnStack = [_programStack lastObject];
if([l_topItemOnStack isKindOfClass:[NSNumber class]])
{
    return [l_topItemOnStack doubleValue];
}

My question : since my l_topItemOnStack is of type id and I didn't cast it into a NSNumber, how am i able to use the [l_topItemOnStack doubleValue].

I guessed that I had to cast it to NSNumber first to access the NSNumber methods...

What am I missing here ?

解决方案

Because Objective-C is a dynamic language, the message names and their declarations are just hints for the compiler - the actual message lookup and sending occurs at runtime. So even if the compiler doesn't know your object responds to the doubleValue message, it's still able to make your call into

return objc_msgSend(l_topItemOnStack, @selector(doubleValue));

as usually.

Furthermore, the compiler looks up all the selectors that are declared anywhere in the included headers, and tries to find the best match using the actual context - here doubleValue is a unique name - it's declared on NSNumber only, so the compiler assumes that your object is indeed an NSNumber.

If you really want to avoid this, either cast the object when you call the method or initially declare it as an NSNumber.

这篇关于Objective-C理解是KindOfClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆