UserDefaults.standard.object(key)总是为零

问题描述 投票:0回答:3

在我的情况下,UserDefaults.standard.object()总是返回零。我不明白为什么。请帮忙。我使用swift 4.2和Xcode 9.x.我的项目有多个文件:swift和objC。如果我从objC代码(NSUserDefaults ...)设置值,那么一切正常。价值存在。

我在Swift文件中的B级:

import Foundation
@objc class Preferences : NSObject{

    /**
     Сохранение в локальном хранилище данных
     :param: key ключ (название параметра
     :param: value значение - любой тип данных
     */
    public static func saveValue (key:String, value:Any) -> (){
        UserDefaults.standard.set(value, forKey: key)
        UserDefaults.standard.synchronize()
    }

    /**
     Получить данные из локального хранилища
     :param: key ключ (название параметра)
     :returns: Any значение - любой тип данных
     */
    public static func getValue (key:String) -> (Any?){
        let val = UserDefaults.standard.object(forKey: key)
        return val // ------- always NIL
//        if let type1 = val as? String{
//            return type1
//        }else if let type2 = val as? Int{
//            return type2
//        }else if let type3 = val as? Double{
//            return type3
//        }else{
//            return val;
//        }
    }
}

从objC类我先调用swift-func。

objC(检查值):

if (![[Preferences getValueWithKey:@"surname_"] isEqualToString:@""]){
    [surnameF setText:[Preferences getValueWithKey:@"surname_"]];
    [nameF setText:[Preferences getValueWithKey:@"name_"]];
    [patronymicF setText:[Preferences getValueWithKey:@"patronymic_"]];
}

objC(通过调用swift-class设置值):

[DataManager saveDataWithSurname:surname name:name patronymic:patronymic];

Swift文件中的A类:

@objc class DataManager : NSObject{

public static func saveData(surname: String, name: String, patronymic: String){
    //Сохранить локально
    Preferences.saveValue(key: surname, value1: "surname_")
    Preferences.saveValue(key: name, value1: "name_")
    Preferences.saveValue(key: patronymic, value1: "patronymic_")

    let sCommand = SimpleCommand()
    sCommand.command = "setUserData"
    var userData = [String:String]()
    userData["user_surname"] = surname
    userData["user_name"] = name
    userData["user_patronymic"] = patronymic
    sCommand.params["userData"] = userData

    NetHelper.sendJSONPureRequest(
        sCommand: sCommand,
        onSuccess: { (sAnswer) in
            EasyDialog.showAlert(title: "Уведомление", message: sAnswer.messageText!)
    }) { (errMsg) in
        EasyDialog.showAlert(title: "Ошибка", message: errMsg)
    }
}
ios swift nsuserdefaults
3个回答
0
投票

正如讨论func set(_ value: Any?, forKey defaultName: String)

value参数只能是属性列表对象:NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。对于NSArray和NSDictionary对象,其内容必须是属性列表对象。

因此,默认对象必须是属性列表 - 即(或对于集合,实例的组合)NSDataNSStringNSNumberNSDateNSArrayNSDictionary的实例。如果要存储任何其他类型的对象,通常应将其存档以创建NSData的实例。

尝试解决方案here


0
投票

愚蠢的错误:

public static func saveData(surname: String, name: String, patronymic: String){
    //Сохранить локально
    Preferences.saveValue(key: surname, value1: "surname_")
    Preferences.saveValue(key: name, value1: "name_")
    Preferences.saveValue(key: patronymic, value1: "patronymic_")

关键< - >值。 :)


0
投票

Swift 5非常简单

Attempt to set a non-property-list object as an NSUserDefaults

https://stackoverflow.com/questions/19720611/attempt-to-set-a-non-property-list-object-as-an-nsuserdefaults/56625605#56625605

-1
投票

你应该返回简单的对象而不是闭包。此外,synchronize将被弃用,您可以将其删除。

试试这个固定的代码。

public static func saveValue (key: String, value: Any) {
    UserDefaults.standard.set(value, forKey: key)
}

public static func getValue (key:String) -> Any? {
    let val = UserDefaults.standard.object(forKey: key)
    return val
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.