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

如何在UserDefaults中存储最多5个SearchHistory实例,新项替换最旧项

实现最多存储5条搜索历史的UserDefaults扩展

直接上修改后的完整代码,核心是把存储对象从单个SearchHistory改成数组[SearchHistory],同时添加长度控制逻辑:

首先调整UserDefaults的扩展方法:

fileprivate enum UserDefaultKeys: String {
    case userSearchHistory = "userSearchHistory"
}

extension UserDefaults {
    // 获取搜索历史数组
    static func getUserSearchHistory() -> [SearchHistory] {
        guard let data = standard.data(forKey: UserDefaultKeys.userSearchHistory.rawValue) else {
            return []
        }
        do {
            return try JSONDecoder().decode([SearchHistory].self, from: data)
        } catch {
            print("解码搜索历史失败: \(error)")
            return []
        }
    }
    
    // 保存搜索历史,自动控制最多5条
    static func setUserSearchHistory(_ newHistory: SearchHistory) {
        var histories = getUserSearchHistory()
        
        // 可选:去重逻辑,比如根据storeNo移除重复的旧记录
        // histories.removeAll { $0.storeNo == newHistory.storeNo }
        
        // 新记录放在最前面,保证最新的在头部
        histories.insert(newHistory, at: 0)
        
        // 超过5条时删除最旧的最后一条
        if histories.count > 5 {
            histories.removeLast()
        }
        
        do {
            let data = try JSONEncoder().encode(histories)
            standard.set(data, forKey: UserDefaultKeys.userSearchHistory.rawValue)
            standard.synchronize() // iOS10+系统自动同步,手动调用更稳妥
        } catch {
            print("编码搜索历史失败: \(error)")
        }
    }
}

你的SearchHistory结构和枚举保持不变(确保Codable正常工作):

struct SearchHistory: Codable {
    let type: SearchHistoryEnum
    let name: String
    let corpNo: String
    let storeNo: String
    let long: Double
    let lat: Double
}

enum SearchHistoryEnum: Codable {
    case storeSearch
    case jsonSearch
}

调用时直接传入单个SearchHistory对象即可:

let historySearch = SearchHistory(
    type: .storeSearch,
    name: store?.storename ?? "",
    corpNo: store?.corpno ?? "",
    storeNo: store?.storeno ?? "",
    long: longtitude,
    lat: latitude
)
UserDefaults.setUserSearchHistory(historySearch)

关键修改说明:

  • 存储对象从单个实例改为数组,对应解码逻辑同步调整为数组类型
  • 新增记录时先取现有数组,将新记录插入头部,保证顺序是最新到最旧
  • 数组长度超过5时自动移除最后一条(最旧的记录)
  • 用标准JSONEncoder/JSONDecoder替代自定义解析方法,更符合Swift规范且稳定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:45:37