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

隐式Objective-C入口点-[setPeriod_end_date:]已废弃,Subscription类初始化问题

解决KVC中-[setPeriod_end_date:]已废弃警告的办法

嘿,这个警告我之前在处理Swift和KVC交互时也踩过坑!问题根源在于你用了蛇形命名的属性(比如period_end_date),而setValuesForKeys依赖Objective-C的KVC机制,现在这种自动生成的蛇形命名setter方法已经被苹果标记为废弃了。下面给你几个靠谱的解决思路:

方案1:改用Swift风格的驼峰命名属性,手动映射字典键

这是最推荐的做法,符合Swift命名规范,也从根源上避免了警告。

首先把Subscription的属性改成驼峰命名:

class Subscription: NSObject { // 需继承NSObject才能使用KVC,你的代码应该已经继承了
    var id: String = ""
    var card: SCard?
    var planId: String = ""
    var status: String = ""
    var cancelAtPeriodEnd: Int = 0 // 1表示已取消,0表示活跃
    var periodEndDate: String = ""
    var trialEndDate: String = ""
    var benefits: Benefits?
    
    init(dictionary: [String: Any]) {
        super.init()
        // 手动将字典的蛇形键映射到驼峰属性
        id = dictionary["id"] as? String ?? ""
        card = dictionary["card"] as? SCard
        planId = dictionary["plan_id"] as? String ?? ""
        status = dictionary["status"] as? String ?? ""
        cancelAtPeriodEnd = dictionary["cancel_at_period_end"] as? Int ?? 0
        periodEndDate = dictionary["period_end_date"] as? String ?? ""
        trialEndDate = dictionary["trial_end_date"] as? String ?? ""
        benefits = dictionary["benefits"] as? Benefits
    }
}

这种方式虽然需要手动写映射,但完全脱离了对Objective-C KVC自动转换的依赖,代码更清晰,也不会有警告。

方案2:重写setValue(_:forKey:)处理键名映射

如果你不想修改现有属性的命名,可以重写这个方法,针对每个蛇形键手动映射到对应属性:

class Subscription: NSObject {
    var id: String = ""
    var card: SCard?
    var plan_id: String = ""
    var status: String = ""
    var cancel_at_period_end: Int = 0 // 1表示已取消,0表示活跃
    var period_end_date: String = ""
    var trial_end_date: String = ""
    var benefits: Benefits?
    
    init(dictionary: [String: Any]) {
        super.init()
        setValuesForKeys(dictionary)
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        // 针对每个蛇形键手动赋值,避免触发废弃的setter
        switch key {
        case "period_end_date":
            period_end_date = value as? String ?? ""
        case "cancel_at_period_end":
            cancel_at_period_end = value as? Int ?? 0
        case "plan_id":
            plan_id = value as? String ?? ""
        case "trial_end_date":
            trial_end_date = value as? String ?? ""
        default:
            super.setValue(value, forKey: key)
        }
    }
}

不过这种方式不如方案1优雅,毕竟蛇形命名在Swift里不是常规风格。

为什么会出现这个警告?

苹果正在逐步弱化Swift对Objective-C KVC自动转换的支持,蛇形命名的属性会自动生成类似setPeriod_end_date:的Objective-C方法——这种不符合Objective-C命名规范(Objective-C里应该用setPeriodEndDate:)的方法已经被标记为废弃,因此触发了警告。

内容的提问来源于stack exchange,提问作者ElGonzoGonzales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:37:26