calling function in a controller from a class (objective-c)
I'm writing an iPhone application in Objective-C. 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. How do I do this? Please provide an ex开发者_StackOverflow社区ample. Thank you!
One way you can do this is to create a property in your Foo class that references its creator. 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. Now from your Foo class you can call controller methods like this:
[[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? If Foo
is a View, then why would it communicate with your controller?
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?
Alternatively, you should create a @protocol
in Foo and when MainViewController creates Foo, have the MainViewController implements Foo's delegate
.
You should probably check out Cocoa Design Patterns by Erik M. Buck and 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.
精彩评论