如何将“A类”转换为其子类“B类” - Objective-C [英] How to cast 'Class A' to its subclass 'Class B' - Objective-C

查看:207
本文介绍了如何将“A类”转换为其子类“B类” - Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个框架,定义和使用'ClassA',NSObject的子类。我想添加一些变量和功能,所以自然创建了'ClassB','ClassA'的子类



现在我的问题是这个。这个框架中的许多方法返回ClassA的实例,我想将它转换为我的子类。



例如使用以下方法:

   - (ClassA *) doSomethingCool:(int)howCool 



现在在我的代码中,我试试这个:

  ClassB * objB; 
objB =(ClassB *)doSomethingCool(10);

NSLog(@objB className =%@,[objB className]);

这样运行就好了。没有编译或运行时错误或任何东西。但对我来说真奇怪的是输出:

 >> objB className = ClassA

铸造明显失败。不知道发生了什么事情... objB类型是ClassB,但它的className是ClassA,它不会响应任何ClassB方法。



不知道这是怎么可能的...任何人都知道我在这里做错了什么?



我发现了一个类似的帖子,请此处

解决方案

在Objective-C中强制转换对象变量通常是一个错误(有几种情况是正确的,那类的东西)。请注意,您没有投射对象 - 您正在向对象投射指针。然后你有一个类型 ClassB * 的指针,但它仍指向同一个ClassA的实例。



如果你真的想将ClassA的实例转换为ClassB,你需要编写一个ClassB构造方法,它可以从ClassA创建一个ClassB实例。如果你真的需要添加实例变量,这可能是你最好的选择。



正如Jason说的,但是,最好先尝试类别。 p>

I'm using a framework which defines and uses 'ClassA', a subclass of NSObject. I would like to add some variables and functionality so naturally I created 'ClassB', a subclass of 'ClassA'

Now my problem is this. Many of the methods within this framework return instances of 'ClassA' which I would like to cast to my subclass.

For example take this method:

- (ClassA *)doSomethingCool:(int)howCool

Now in my code I try this:

ClassB * objB;
objB = (ClassB *)doSomethingCool(10); 

NSLog(@"objB className = %@", [objB className]);

This runs just fine. No compile or runtime errors or anything. But what is really odd to me is the output:

>> "objB className = ClassA"

The casting obviously failed. Not sure what's happened at this point... objB is typed as 'ClassB', but it's className is 'ClassA' and it won't respond to any 'ClassB' methods.

Not sure how this is possible... Anyone know what I am doing wrong here?

I found a similar post which is exact opposite of what I'm asking here

解决方案

Casting object variables in Objective-C is usually a mistake (there are a few cases where it's right, but never for this sort of thing). Notice that you aren't casting an object — you're casting a pointer to an object. You then have a pointer of type ClassB*, but it still points to the same instance of ClassA. The thing pointed to hasn't changed at all.

If you really want to convert instances of ClassA to ClassB, you'll need to write a ClassB constructor method that can create a ClassB instance from a ClassA. If you really need to add instance variables, this might be your best choice.

As Jason said, though, it's often a good idea to try a category first.

这篇关于如何将“A类”转换为其子类“B类” - Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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