You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Framework中访问AppDelegate的自定义变量与方法?

iOS Framework访问AppDelegate自定义成员的解决方案

方案一:自定义协议(推荐)

在Framework里定义一个继承自UIApplicationDelegate的自定义协议,把需要访问的自定义变量和方法声明进去:

// Framework内的代码
public protocol AppCustomDelegate: UIApplicationDelegate {
    var customVariable: String { get set }
    func customMethod()
}

修改SampleManager的delegate类型为这个自定义协议:

public class SampleManager {
    public static let shared = SampleManager()
    public weak var delegate: AppCustomDelegate?

    func doWhateverYouWant() {
        // 直接访问自定义成员
        delegate?.customVariable = "demo"
        delegate?.customMethod()
    }
}

最后让主App的AppDelegate遵守这个协议:

// 主App的AppDelegate
class AppDelegate: UIResponder, AppCustomDelegate {
    var customVariable: String = ""
    
    func customMethod() {
        // 实现你的业务逻辑
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        SampleManager.shared.delegate = self
        return true
    }
    // 系统默认方法保持不变...
}

方案二:类型转换(临时快速方案)

如果不想定义协议,也可以在访问时把delegate强转成你的AppDelegate类型,但这种方式耦合度高,不推荐长期使用:

// Framework内SampleManager的方法
func doWhateverYouWant() {
    guard let appDelegate = delegate as? AppDelegate else {
        return
    }
    // 访问自定义内容
    appDelegate.customVariable = "demo"
    appDelegate.customMethod()
}

注意:要让Framework能识别AppDelegate,需要把AppDelegate标记为public,或者在Framework中导入主App的模块(会增加依赖,谨慎使用)。

两种方案对比

  • 自定义协议:完全解耦Framework和主App,符合面向接口编程的最佳实践,后续主App修改AppDelegate结构也不会影响Framework。
  • 类型转换:实现简单,但依赖主App的具体类结构,一旦主App的AppDelegate改名或修改成员,Framework会直接报错,只适合临时调试或简单场景。

内容的提问来源于stack exchange,提问作者Muhammad Danish Qureshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:50:24