在多个类中重用方法

发布于 2024-09-29 14:39:40 字数 489 浏览 1 评论 0原文

我刚刚在一个具有多个不同 UIViewControllers 的应用程序中实现了 iAd。 我在每个应用程序中都有 - (void)bannerViewDidLoadAd:(ADBannerView *)banner 和 < code>- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error 显示和隐藏横幅,以及在 viewDidLoad 期间创建横幅的设置方法。

我通过让第一个 UIViewController 中的所有内容正常工作,然后将代码以及 ivar 声明、属性等复制到其他每个控制器来做到这一点

...不可能是对的。每次我改变一个,我就必须把它们全部改变。我的问题(最后!)是:有没有办法一次性编写这些方法,以便所有类都可以访问它们?

谢谢!

I've just implemented iAds in an app with several distinct UIViewControllers. I have the delegate methods in each one for - (void)bannerViewDidLoadAd:(ADBannerView *)banner and - (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error that show and hide the banner, along with a setup method that creates a banner during viewDidLoad.

I did this by getting everything working in the first UIViewController and then copying the code to each of the other controllers, along with the ivar declarations, properties, etc...

This can't be right. Every time I change one, I have to change them all. My question (finally!) is: Is there a way to write these methods once so that all classes have access to them?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

短暂陪伴 2024-10-06 14:39:40

如果子类化没有意义,我建议创建 ac 函数。

如果此函数伴随其他相关函数,请将其与其相关函数一起放入库中。如果列表变得很长,类可能是更好的选择。

如果此函数是独立的并且特定于一个应用程序/项目,则只需创建一个文件来声明所有这些奇怪的位(如果它们必须在多个翻译中重用)。如果位文件确实很大,则可能存在一些设计问题。

有些人可能会推荐 objc 类别实例方法。我通常会避免分类,因为出错的机会不必要地高。 C 和 C++ 函数/类型是链接的,如果不被引用,则很容易被删除。对于类别,您不能链接,并且不得删除它和方法中使用的符号。

如果两者在概念上(或物理上)绑定,您可以将其作为单例的实例方法包含在内。否则,我建议将它们分开。

i recommend creating a c function if subclassing does not make sense.

if this function accompanies other related functions, place it in a library with its relatives. if the list becomes long, a class may have been a better choice.

if this function is standalone and specific to one app/project, then just create a file which declares all of these odd bits (if they must be reused across multiple translations). if the file of bits is really large, there's likely a few design issues.

some people may recommend an objc category instance method. i generally avoid categories because the chance for error is unnecessarily high. C and C++ functions/types, are linked and easily stripped if they are not referenced. with a category, you don't link, and it and the symbols used in the method must not be stripped.

you could include this as an instance method for your singleton, if the two are conceptually (or physically) bound. otherwise, i recommend keeping them separate.

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