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

集成RevenueCat后无法访问静态变量/类,请求技术排查

排查Swift中SettingsController静态变量无法访问的问题

1. 检查静态变量的定义与访问控制

确保静态变量的语法和访问权限正确:

  • 同Target内使用默认internal访问级别即可,跨Target需显式声明public static
  • 示例代码:
class SettingsController: UIViewController {
    // 同Target用默认权限,跨Target改为 public static
    static var subscriptionStatus: Bool = false

    func fetchSubscriptionStatus() {
        Purchases.shared.getCustomerInfo { [weak self] customerInfo, error in
            guard let customerInfo = customerInfo else { return }
            // 注意用类名直接更新静态变量
            SettingsController.subscriptionStatus = customerInfo.entitlements.active.contains("your_entitlement_id")
        }
    }
}

2. 确认异步更新的时机

getCustomerInfo是异步方法,MainViewController访问时可能变量还未更新:

  • 可通过通知中心监听状态变化,确保回调完成后再读取变量:
// SettingsController的回调中发送通知
Purchases.shared.getCustomerInfo { customerInfo, error in
    guard let info = customerInfo else { return }
    SettingsController.subscriptionStatus = info.entitlements.active.contains("entitlement_id")
    NotificationCenter.default.post(name: NSNotification.Name("SubscriptionStatusUpdated"), object: nil)
}

// MainViewController中监听通知
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(updateSubscriptionUI), name: NSNotification.Name("SubscriptionStatusUpdated"), object: nil)
}

@objc private func updateSubscriptionUI() {
    let status = SettingsController.subscriptionStatus
    // 根据状态更新UI
}

3. 排查委托失效的关键点

如果委托方式无效,检查以下两点:

  • 委托对象是否已正确赋值(需在跳转SettingsController时设置settingsVC.delegate = self)
  • 委托协议是否标记AnyObject避免循环引用,方法是否正确实现:
protocol SubscriptionStatusDelegate: AnyObject {
    func didUpdateSubscriptionStatus(isSubscribed: Bool)
}

class SettingsController: UIViewController {
    weak var delegate: SubscriptionStatusDelegate?

    func fetchStatus() {
        Purchases.shared.getCustomerInfo { info, error in
            let isSubscribed = info?.entitlements.active.contains("entitlement_id") ?? false
            self.delegate?.didUpdateSubscriptionStatus(isSubscribed: isSubscribed)
        }
    }
}

// MainViewController实现委托
class MainViewController: UIViewController, SubscriptionStatusDelegate {
    func pushToSettings() {
        let settingsVC = SettingsController()
        settingsVC.delegate = self
        navigationController?.pushViewController(settingsVC, animated: true)
    }

    func didUpdateSubscriptionStatus(isSubscribed: Bool) {
        // 处理订阅状态
    }
}

4. 清理项目缓存

静态变量不生效可能是缓存问题:

  • 执行Cmd+Shift+K清理项目,再Cmd+B重新编译
  • 手动删除DerivedData文件夹(路径:~/Library/Developer/Xcode/DerivedData)

内容的提问来源于stack exchange,提问作者Furkan Tümay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:02:56