Objective C中不同类之间的方法调用 [英] method call between different class in Objective c

查看:94
本文介绍了Objective C中不同类之间的方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将方法从一个类调用到另一个类 其中有两个来自两个不同父类的类.假设一个来自 UIImage类和UIViewController类中的另一个?

Is it possible to call method from one class to another where two classes from two different parent class. Suppose one from UIImage class and another from UIViewController class?

推荐答案

是的,关于Objective-C的一件很酷的事情是,即使没有响应,您也可以在任何对象上调用方法.尽管不如Objective-C的父亲SmallTalk健壮(是的,SmallTalk是爸爸,C是妈妈,别问了),但它仍然非常强大.假设您有这样的事情:

Yes, one of the cool things about Objective-C is that you can call a method on any object, even if it doesn't respond. Although not as robust as in Objective-C's father, SmallTalk (yes, SmallTalk is the dad and C is the mom, don't ask), it's still pretty powerful. So let's say you have something like this:


- (void)doSomethingToThis: (id)thisObject
{
  [thisObject doSomething];
}

然后再...


//...
  UIImage *thisImage = ...
  UIViewController *thisController = ...

  [self doSomethingToThis: thisImage];
  [self doSomethingToThis: thisController];
//...

这样的编译就可以了,但是如果UIImageUIViewController都不响应doSomething时会被警告,那么最终可能会导致崩溃(具体取决于设置编译器标志的方式) ,但我相信默认情况下会崩溃).

Something like this will compile just fine, but be warned if UIImage and UIViewController don't both respond to doSomething, then you could end up with a crasher (depends on how you have the compiler flags set, but I believe by default you'll get a crash).

这篇关于Objective C中不同类之间的方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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