且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective C中不同类之间的方法调用

更新时间:2022-06-22 22:29:14

是的,关于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).