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

如何高效将多种不同加密货币对象保存至Core Data?

嘿,恭喜你搞定第一个应用还完成了代码优化!针对你现在Core Data保存加密货币遇到的瓶颈,这里有几个实用的最优方案,帮你摆脱一堆if判断的繁琐:

方案一:创建统一的加密货币模型类/结构体

这是最推荐的面向对象方案,把加密货币的所有属性封装成一个模型,让Core Data的保存方法直接接收这个模型,彻底告别分支判断。

首先定义一个包含所有必要属性的结构体:

struct CryptoCurrency {
    let name: String
    let code: String
    let symbol: String
    let placeholder: String
    let initialAmount: String
}

然后修改你的CoreDataHandler的saveObject方法,让它接收这个模型作为参数:

static func saveObject(_ crypto: CryptoCurrency) {
    // 创建Core Data实体对象
    let newCryptoEntity = CryptoEntity(context: persistentContainer.viewContext)
    
    // 直接从模型中读取属性赋值
    newCryptoEntity.name = crypto.name
    newCryptoEntity.code = crypto.code
    newCryptoEntity.symbol = crypto.symbol
    newCryptoEntity.placeholder = crypto.placeholder
    newCryptoEntity.amount = crypto.initialAmount
    
    // 执行保存
    do {
        try persistentContainer.viewContext.save()
    } catch {
        print("Core Data保存失败:\(error.localizedDescription)")
    }
}

调用的时候,不管用户选择哪种加密货币,只需要创建对应的模型实例即可:

// 比如用户添加Augur REP
let augurREP = CryptoCurrency(
    name: "Augur",
    code: "augur",
    symbol: "REP",
    placeholder: "REP Amount",
    initialAmount: "0.0000"
)
CoreDataHandler.saveObject(augurREP)

// 新增其他币种时,只需要创建新的模型实例,完全不用修改保存逻辑
let bitcoin = CryptoCurrency(
    name: "Bitcoin",
    code: "bitcoin",
    symbol: "BTC",
    placeholder: "BTC Amount",
    initialAmount: "0.0000"
)
CoreDataHandler.saveObject(bitcoin)

这个方案的优势是可读性强、扩展性高,后续新增币种或者修改属性,只需要调整模型或实例化代码,核心的保存逻辑完全不用动。

方案二:用预定义字典映射币种信息

如果暂时不想新增模型类,可以把所有支持的币种信息提前存在一个字典里,用用户选择的币种名称作为key,直接匹配对应的属性值。

先定义映射字典:

// key是用户选择的币种名称(比如"Augur REP"),value是包含所有属性的元组
let cryptoInfoMap: [String: (name: String, code: String, symbol: String, placeholder: String, amount: String)] = [
    "Augur REP": ("Augur", "augur", "REP", "REP Amount", "0.0000"),
    "Bitcoin": ("Bitcoin", "bitcoin", "BTC", "BTC Amount", "0.0000"),
    "Ethereum": ("Ethereum", "ethereum", "ETH", "ETH Amount", "0.0000"),
    // 其他币种依次添加
]

然后调用保存方法时直接从字典取值:

if let cryptoInfo = cryptoInfoMap[addedCrypto] {
    CoreDataHandler.saveObject(
        name: cryptoInfo.name,
        code: cryptoInfo.code,
        symbol: cryptoInfo.symbol,
        placeholder: cryptoInfo.placeholder,
        amount: cryptoInfo.amount
    )
} else {
    // 处理用户选择了不支持的币种的情况
    print("暂不支持该加密货币")
}

这个方案适合币种数量固定、不需要频繁新增的场景,维护起来只需要更新字典即可,代码也比较简洁。

方案三:通用属性字典保存(进阶)

如果想让保存逻辑更通用,可以让CoreDataHandler支持传入属性字典,通过KVC的方式给实体赋值:

extension CoreDataHandler {
    static func saveCrypto(with attributes: [String: Any]) {
        let newCrypto = CryptoEntity(context: persistentContainer.viewContext)
        
        // 遍历属性字典,通过KVC赋值
        for (key, value) in attributes {
            if newCrypto.responds(to: Selector(key)) {
                newCrypto.setValue(value, forKey: key)
            }
        }
        
        // 保存上下文
        do {
            try persistentContainer.viewContext.save()
        } catch {
            print("Core Data保存失败:\(error.localizedDescription)")
        }
    }
}

调用时传入对应属性的字典:

let augurAttributes: [String: Any] = [
    "name": "Augur",
    "code": "augur",
    "symbol": "REP",
    "placeholder": "REP Amount",
    "amount": "0.0000"
]
CoreDataHandler.saveCrypto(with: augurAttributes)

这个方案要注意属性名必须和Core Data实体的属性严格一致,否则会赋值失败,适合对Core Data比较熟悉的开发者。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:51:00