Iphone: writing some methods in a seperate file to acess from everywhere

心不动则不痛 提交于 2019-12-22 09:39:00

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/2858118/iphone-writing-some-methods-in-a-seperate-file-to-acess-from-everywhere

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