views:

36

answers:

1

Hey,

here is a quick question, i have my couple view controllers classes, and have some other classes. i've found my self creating some methods in all of their implementation files, which are doing the same.

i would like to write some of my methods in a seperate file, and import this file into my view controllers. therefore, i will be able to run those methods from my current view controller,

In case this method will require a change, i will not need to re-write it in all my implementaion files.

Let me Sharp just one thing. I do not want to create a new object! and instantiate it. i do want to be able to run this method just like i was doing: [self doSomething];

Please help to understand how this should be done.

i.e. i have 3 view controllers, each has the bellow method:

-(void)doSomething:(id)sender{
//doing something
}

just want to have this doSomething method defined in one place, and i could access it from my view controllers by running: [self doSomething];

is it possible?

Thanks in advance.

+2  A: 

You want to do this by subclassing. First create a class where you want all your shared methods, as a subclass of UIViewController, let's call it BaseViewController. For example you'd have this in your header file:

@interface BaseViewController: UIViewController 
{
}
-(void)doSomething:(id)sender;
@end

And then the corresponding definition in your .m file.

Now when you want to create a new UIViewController subclass which has the shared methods make the new class a subclass of BaseViewController not UIViewController, like so:

@interface MyViewController: BaseViewController
{
}
@end
pheelicks
Hey, Perfect, working as charm,but one more question, can a class be a subclass of more than one class?i mean, can i do: @interface PersistenceViewController : UIViewController :SQLcontroller {as you can understand from above, i do want to create a class for all my SQLs, (accessing the DB, open/fetch/close,create tables...)You got the point.
Dror Sabbag
It is best to put database access in another class entirely, and then put an instance of this class into your view controller. Think of DB as being in the 'model' part of the model, view, controller pattern.
Colin Gislason
Hey Colin, it sounds like this is what i was looking for, can you please give me a small example of how this should be done?
Dror Sabbag
@Dror Sabbag - Try googling MVC :)
willcodejavaforfood
Hey, I've figured it out, Thanks all for the answers!
Dror Sabbag