iPhone:在单独的文件中编写一些方法以便从任何地方访问
这是一个简单的问题, 我有几个视图控制器类,还有一些其他类。 我发现我自己在所有实现文件中创建了一些方法,它们的作用相同。
我想将我的一些方法写在一个单独的文件中, 并将此文件导入到我的视图控制器中。 因此,我将能够从当前的视图控制器运行这些方法,
如果此方法需要更改,我不需要在所有实现文件中重新编写它。
让我夏普讲一件事。我不想创建一个新对象!并实例化它。 我确实希望能够像我一样运行这个方法:[self doSomething];
请帮助理解应该如何完成此操作。
IE 我有 3 个视图控制器,每个都有以下方法:
-(void)doSomething:(id)sender{
//doing something
}
只想在一个地方定义这个 doSomething 方法, 我可以通过运行以下命令从视图控制器访问它: [自己做某事];
是否可以?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想通过子类化来做到这一点。首先创建一个您想要所有共享方法的类,作为 UIViewController 的子类,我们将其称为 BaseViewController。例如,您的头文件中应包含以下内容:
然后 .m 文件中包含相应的定义。
现在,当您想要创建一个具有共享方法的新 UIViewController 子类时,请使新类成为 BaseViewController 而不是 UIViewController 的子类,如下所示:
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:
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: