views:

60

answers:

3

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 example. Thank you!

A: 

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];
darren
This is really complex. It sounds like he just needs to read and learn a bit more about Objective-C and Cocoa in general first.
Marc W
A: 

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.

marcc
Foo is actually just a class I created which is a subclass of NSObject. It's not a model or a controller.
Mark Johnson
A: 

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.

Nimrod