gpt4 book ai didi

ios - 在多个 View Controller 中轻松重用一堆代码的最佳实践是什么?

转载 作者:可可西里 更新时间:2023-11-01 05:44:10 26 4
gpt4 key购买 nike

我是编程新手,想知道某种(最佳)实践:

假设我们有一个带有多个 View Controller 的应用程序。在我们的例子中,其中大部分都需要提醒用户某些情况的功能,使用事件指示器或依赖于其他类似的通用功能。到目前为止,我已经学会了如何实现这些方法,但在需要时只是将整串代码复制到每个 View Controller 。这样做,每个 View Controller 都会填满大量额外的代码。我知道可以通过将代码移动到 View Controller 的顶部,在类括号之外来使代码有点“全局”。但是由于我们需要确保在调用这些方法时将某些 subview 添加到正确的 View Controller 中,所以我不确定最好的方法是什么——一般来说——会是什么。

在定义这种在多个 View Controller 中使用的 - 比方说 - 警报行为(定义变量/常量及其所需的方法)时,是否存在与我的方法不同的常用做法?

最佳答案

Objective-C 提供了两种重用代码的通用方法:

  1. 继承基类,以及
  2. 使用共享功能。

第一种情况很简单:如果您需要多个 View Controller 中的特定功能,请使用共享方法创建一个基本 View Controller ,然后从中派生其他 View Controller :

@interface BaseViewController : UIViewController
-(void)sharedMethodOne;
-(void)sharedMethodTwo;
@end
@interface FirstViewController : BaseViewController
...
@end
@interface SecondViewController : BaseViewController
...
@end
@interface ThirdViewController : BaseViewController
...
@end

第二种情况可以实现为带有类方法的辅助类(即使用 + 而不是 -)或使用独立的 C 函数。

关于ios - 在多个 View Controller 中轻松重用一堆代码的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26195402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com