开发者

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

here is a quick question, i have my couple vi开发者_高级运维ew 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜