在我的代码中,当用户进入应用程序时,我给他/她一个令牌,并用UserDefaults保存它,然后在该应用程序中的其他地方,用户可以将地址设置为主地址,然后由UserDefaults保存。 当我首先这样做时,它将删除使用用户默认值保存在constantKey.token中的令牌,然后在地址constant.address中放入“ 65”!尽管地址不是“ 65”
UserDefaults.standard.set(self.Main[indexPath.row].AddressLine, forKey: constantAddress.addressLine)
////
UserDefaults.standard.set(self.Main[indexPath.row].ProvinceName, forKey: ConstantsKey.stateName)
UserDefaults.standard.set(self.Main[indexPath.row].ProvinceId, forKey: constantAddress.stateId)
UserDefaults.standard.set(self.Main[indexPath.row].CityName, forKey: constantAddress.cityName)
UserDefaults.standard.set(self.Main[indexPath.row].CityId, forKey: constantAddress.cityId)
UserDefaults.standard.set(self.Main[indexPath.row].AddressLine, forKey: constantAddress.addressLine)
UserDefaults.standard.set(self.Main[indexPath.row].PostalCode, forKey: constantAddress.postalCode)
UserDefaults.standard.set(self.Main[indexPath.row].Tel, forKey: constantAddress.telephone)
UserDefaults.standard.set(self.Main[indexPath.row].Mobile, forKey: constantAddress.mobile)
UserDefaults.standard.set(self.Main[indexPath.row].Id, forKey: constantAddress.Id)
class constantAddress {
static var Id = ""
static var stateName = ""
static var stateId = "0"
static var cityName = ""
static var cityId = "0"
static var addressLine = ""
static var postalCode = ""
static var telephone = ""
static var mobile = ""
}
它不会将项目的值保存到constantAddress
从用户定义中获取数据
StateLbl.text = UserDefaults.standard.string(forKey: constantAddress.stateName)
CityLbl.text = UserDefaults.standard.string(forKey: constantAddress.cityName)
AddressLbl.text = UserDefaults.standard.string(forKey: constantAddress.addressLine)
PostalCodeLbl.text = UserDefaults.standard.string(forKey: constantAddress.postalCode)
TelLbl.text = UserDefaults.standard.string(forKey: constantAddress.telephone)
MobileLbl.text = UserDefaults.standard.string(forKey: constantAddress.mobile)
答案 0 :(得分:0)
您使用不同的键来设置UserDefaults
并从中获取
UserDefaults.standard.set(self.Main[indexPath.row].ProvinceName, forKey: ConstantsKey.stateName)
使用ConstantsKey.stateName
StateLbl.text = UserDefaults.standard.string(forKey: constantAddress.stateName)
使用constantAddress.stateName
假设ConstantsKey.stateName
具有字符串值,那么您需要说的是...
StateLbl.text = UserDefaults.standard.string(forKey: ConstantsKey.stateName)
请仔细阅读UserDefaults
的文档…https://developer.apple.com/documentation/foundation/userdefaults