简体   繁体   English

从类中调用控制器中的函数(目标-c)

[英]calling function in a controller from a class (objective-c)

I'm writing an iPhone application in Objective-C. 我正在用Objective-C编写一个iPhone应用程序。 I created a class (Foo.m) which I would like to be able to call a method in the controller (MainViewController.m) which instantiated it. 我创建了一个类(Foo.m),希望能够在实例化该控制器的控制器(MainViewController.m)中调用该方法。 How do I do this? 我该怎么做呢? Please provide an example. 请提供一个例子。 Thank you! 谢谢!

One way you can do this is to create a property in your Foo class that references its creator. 一种实现方法是在Foo类中创建一个引用其创建者的属性。 You should not retain this reference to avoid circular references, but the code might look like the following 您不应保留此引用以避免循环引用,但是代码可能类似于以下内容

-(void)yourControllerClassMethod{
    Foo* f = [[Foo alloc] init];
    [f setOwnder:self];
}

In this case, your Foo class has a property called owner which is set when the Controller class makes a new Foo instance. 在这种情况下,您的Foo类具有一个名为owner的属性,该属性在Controller类创建新的Foo实例时设置。 Now from your Foo class you can call controller methods like this: 现在,从Foo类中,您可以像下面这样调用控制器方法:

[[self owner] callSomeControllerMethod];

First of all, I'd recommend reading some design patterns books. 首先,我建议您阅读一些设计模式书籍。 If your Foo class is a Model, then why would your model communicate with the Controller? 如果您的Foo类是Model,那么为什么您的模型会与Controller通信? If Foo is a View, then why would it communicate with your controller? 如果Foo是View,那么为什么它会与您的控制器通信?

Now, while I suspect your app has a design issue with the way you are structuring the code, there are ways to do this. 现在,尽管我怀疑您的应用在构造代码的方式上存在设计问题,但仍有一些方法可以做到这一点。

When MainViewController.m instantiates Foo, can you pass self in and have Foo retain a reference to it? 当MainViewController.m实例化Foo时,您可以传递self并让Foo保留对它的引用吗?

Alternatively, you should create a @protocol in Foo and when MainViewController creates Foo, have the MainViewController implements Foo's delegate . 另外,您应该在Foo中创建一个@protocol ,当MainViewController创建Foo时,让MainViewController实现Foo的delegate

You should probably check out Cocoa Design Patterns by Erik M. Buck and Donald A. Yacktman. 您可能应该查看Erik M. Buck和Donald A. Yacktman撰写的《 可可设计模式》 It's an amazingly excellent book and it's quite comprehensible even if you aren't already familiar with design patterns in general. 这是一本非常出色的书,即使您对一般的设计模式还不熟悉,也可以理解。

It sounds like what you want to do is what the other guys were saying which is a pattern called Delegation. 听起来您想要做的就是其他人说的话,这是一种称为授权的模式。 To see how delegation works, look at all of the built in classes that use it. 若要查看委派的工作原理,请查看所有使用委派的内置类。 Anything that has a delegate property and a protocol like UIBlablaDelegate is using delegation and you can do the same thing with your classes. 任何具有delegate属性和协议(如UIBlablaDelegate都在使用委托,并且您可以对类进行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM