iPhone:在单独的文件中编写一些方法以便从任何地方访问

发布于 2024-09-02 10:51:23 字数 479 浏览 5 评论 0原文

这是一个简单的问题, 我有几个视图控制器类,还有一些其他类。 我发现我自己在所有实现文件中创建了一些方法,它们的作用相同。

我想将我的一些方法写在一个单独的文件中, 并将此文件导入到我的视图控制器中。 因此,我将能够从当前的视图控制器运行这些方法,

如果此方法需要更改,我不需要在所有实现文件中重新编写它。

让我夏普讲一件事。我不想创建一个新对象!并实例化它。 我确实希望能够像我一样运行这个方法:[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿咻 2024-09-09 10:51:23

您想通过子类化来做到这一点。首先创建一个您想要所有共享方法的类,作为 UIViewController 的子类,我们将其称为 BaseViewController。例如,您的头文件中应包含以下内容:

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

然后 .m 文件中包含相应的定义。

现在,当您想要创建一个具有共享方法的新 UIViewController 子类时,请使新类成为 BaseViewController 而不是 UIViewController 的子类,如下所示:

@interface MyViewController: BaseViewController
{
}
@end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文