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

Swift 4中使用UserDefaults遇到问题,寻求技术协助

Fixing Your Swift 4 UserDefaults Code for Storing User Details

Hey there, let's work through the issues in your UserDefaults implementation and make it more reliable. First, we'll fix the obvious syntax problem, then look at ways to make this code cleaner and less error-prone.

1. Fix the Incomplete Syntax

Your code cuts off mid-line when setting the user_Id value—here's the corrected full method:

import Foundation
class Utility: NSObject {
    func storeBaseDetail(firstname:String, lastname:String, picStr:String, email:String, usrname:String, user_Id:String) {
        UserDefaults.standard.set(firstname, forKey: "firstname")
        UserDefaults.standard.set(lastname, forKey: "lastname")
        UserDefaults.standard.set(picStr, forKey: "picStr")
        UserDefaults.standard.set(email, forKey: "email")
        UserDefaults.standard.set(usrname, forKey: "usrname")
        UserDefaults.standard.set(user_Id, forKey: "user_Id") // Completed this line
    }
}

2. Eliminate Typo Risks with Key Constants

Hardcoding string keys is easy to mess up—one typo will break your data retrieval later. Instead, define a set of constants to keep your keys consistent:

private enum UserDefaultsKeys: String {
    case firstname, lastname, picStr, email, usrname, user_Id
}

// Use them in your method like this:
UserDefaults.standard.set(firstname, forKey: UserDefaultsKeys.firstname.rawValue)

3. Use Codable for Scalable, Clean Storage

Storing each field individually gets messy as your user model grows. Swift 4's Codable protocol lets you wrap all user details in a struct and save/retrieve it in one go:

Step 1: Define a User Model Struct

struct UserBaseDetail: Codable {
    let firstname: String
    let lastname: String
    let picStr: String
    let email: String
    let usrname: String
    let user_Id: String
}

Step 2: Update Your Utility Methods

class Utility: NSObject {
    private enum UserDefaultsKeys: String {
        case userBaseDetail
    }

    func storeBaseDetail(_ userDetail: UserBaseDetail) {
        do {
            let encodedData = try JSONEncoder().encode(userDetail)
            UserDefaults.standard.set(encodedData, forKey: UserDefaultsKeys.userBaseDetail.rawValue)
        } catch {
            print("Failed to encode user details: \(error.localizedDescription)")
        }
    }

    func retrieveBaseDetail() -> UserBaseDetail? {
        guard let storedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.userBaseDetail.rawValue) else {
            return nil
        }
        do {
            return try JSONDecoder().decode(UserBaseDetail.self, from: storedData)
        } catch {
            print("Failed to decode user details: \(error.localizedDescription)")
            return nil
        }
    }
}

4. Quick Note on Synchronization

In Swift 4+, you don't need to call UserDefaults.standard.synchronize()—iOS handles persistent storage automatically. Only use it if you have a specific need to force immediate writing (though Apple discourages this for performance reasons).

Bonus: Data Size Consideration

If picStr is a base64-encoded image, UserDefaults isn't the best home for it. UserDefaults is designed for small, lightweight data (like preferences). For images or larger datasets, save the file to the app's documents directory instead.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:57:55