gpt4 book ai didi

ios - 数组和用户默认值的操作

转载 作者:行者123 更新时间:2023-11-30 11:21:16 31 4
gpt4 key购买 nike

我需要一个代码来将数据写入板,

variables:

favoriteKey String "favoriteProducts1"
String productId "803566"


removeProductToFavorites (favoriteKey: "favoriteProducts1", productId: productsObjectArray [sender.tag] .code!)

@objc func favoriteBtnPressed1 (_ sender: UIButton) {
        let productStatus = checkProductFavoriteIsAvailable (favoriteKey: "favoriteProducts1", productId: productsObjectArray [sender.tag] .code!)
        if productStatus == true {
            removeProductToFavorites (favoriteKey: "favoriteProducts1", productId: productsObjectArray [sender.tag] .code!)
        } else {
            saveProductToFavorites (favoriteKey: "favoriteProducts1", productId: productsObjectArray [sender.tag] .code!)
        }
    }
    
    
func checkProductFavoriteIsAvailable (favoriteKey: String, productId: String) -> Bool {
        var status = false
        if let arr = UserDefaults.standard.array (forKey: favoriteKey) as? [String] {
            status = true
        }
        return status
    }
    
    func saveProductToFavorites (favoriteKey: String, productId: String) {
        var favoriteArray = UserDefaults.standard.array (forKey: favoriteKey) as? [String]
        favoriteArray? .append (productId)
        UserDefaults.standard.set (favoriteArray, forKey: productId)
    }
    
    func removeProductToFavorites (favoriteKey: String, productId: String) {
        
    }
    

我需要在 UserDefaults 文件中编写一个数组,其中包含最喜欢的产品列表。

以上代码的目的是:1. checkProductFavoriteIsAvailable - 如果数组已包含产品代码,则此函数返回 true;如果不包含,则返回 false2. saveProductToFavorites - 将新数字(字符串)保存到数组和文件中3.从数组和文件中删除选定的产品代码

我可以寻求帮助吗?

更新

我的调试:http://serwer1356363.home.pl/pub/debug.png

最佳答案

这两个函数用于将产品 ID 添加到收藏夹和从收藏夹中删除产品 ID。

saveProductToFavorites 首先检查 UserDefaults 中是否存在数组。如果是,则在数组不包含 ID 的情况下添加该 ID。如果不是,它会创建一个新数组。最后数组被保存回来

func saveProductToFavorites(favoriteKey: String, productId: String) {
if var favoriteArray = UserDefaults.standard.stringArray(forKey: favoriteKey) {
if !favoriteArray.contains(productId) {
favoriteArray.append(productId)
UserDefaults.standard.set(favoriteArray, forKey: favoriteKey)
}
} else {
let favoriteArray = [productId]
UserDefaults.standard.set(favoriteArray, forKey: favoriteKey)
}
}

removeProductFromFavorites 如果数组和 ID 存在,则删除 ID

func removeProductFromFavorites(favoriteKey: String, productId: String) {
guard var favoriteArray = UserDefaults.standard.stringArray(forKey: favoriteKey),
let index = favoriteArray.index(of: productId) else { return }
favoriteArray.remove(at: index)
UserDefaults.standard.set(favoriteArray, forKey: favoriteKey)
}

关于ios - 数组和用户默认值的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51245290/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com