method call between different class in Objective c

别来无恙 提交于 2019-12-08 06:36:10

问题


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?


回答1:


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];
}

Then later...

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

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

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).




回答2:


You probably want to do something like what is said in this answer of another question:

Objective-C : Call a method from another class in addTarget:action:forControlEvents



来源:https://stackoverflow.com/questions/1496281/method-call-between-different-class-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!