swift - 如何使用自定义类型存储和检索变量

标签 swift nsobject codable nscoding

我有一个类型为 ETIdentity 的变量 identity,我需要将其存储在 ViewController1 中并在 ViewController2 中检索,

View Controller 1

//Variables
var activationCodeFromCore, serialNumberFromCore, entityNameFromCore, deviceIdFromCore, registrationCodeFromCore, entityFromCore: String?
    var activationCode, serialNumber, entityName, deviceId, registrationCode, entity: String?
    var counter: Int = 0
var storedIdentity: ETIdentity?

下面是我需要保留的storedIdentity

let storedIdentity = BridgeSDKUtils.performClassicActivation("26586-05858", withActivationCode: "8998-6857-1357-1870", "entidad0");
        GlobalIdentity.identity = storedIdentity;
func softTokenDataService() {

        let storedIdentity = BridgeSDKUtils.performClassicActivation("26586-05858", withActivationCode: "8998-6857-1357-1870", "entidad0");
        GlobalIdentity.identity = storedIdentity;

        self.activationCode = "8998-6857-1357-1870"
        self.serialNumber = "26586-05858"
        self.entityName = "entityData\(counter)"
        self.deviceId = "\(String(describing: storedIdentity?.deviceId))"
        self.registrationCode = "\(String(describing: storedIdentity?.registrationCode))"
        self.entity = "\(storedIdentity!)"
    }

...

func getEntityCore()
    {
        //Variables that are going to be stored
        self.activationCodeFromCore = activationCode
        self.serialNumberFromCore = serialNumber
        self.entityNameFromCore = entityName
        self.deviceIdFromCore = deviceId
        self.registrationCodeFromCore = registrationCode
        self.entityFromCore = storedIdentity
    }

...

//SecureStorage Function
func saveEntityToCoreData()-> Bool {

        self.softTokenDataService()

        var SavedItem:Bool = true

        var arr : [[String: Any]] = [[
            "activationCode": self.activationCodeFromCore,
            "serialNumber": self.serialNumberFromCore,
            "entityName": self.entityNameFromCore,
            "deviceId": self.deviceIdFromCore,
            "registrationCode": self.registrationCodeFromCore,
            "entity": self.entityFromCore]]

        let jsonData = try! JSONSerialization.data(withJSONObject: arr, options: [.prettyPrinted])
        let json = String(data: jsonData, encoding: String.Encoding.utf8)!

        if self.saveRutSwitchOn
        {
            SecureData.save(key: "entityData0)", data: json.data(using: .utf8)!)
        }
        SavedItem = self.saveRutSwitchOn

        return SavedItem
    }

ViewController2

struct Person {
    var activationCode: String
    var serialNumber: String
    var entityName: String
    var deviceId: String
    var registrationCode: String
    var entity: String
}

struct EntityModel: Codable {
    let activationCode, serialNumber, entityName, deviceId, registrationCode, entity: String?
}

if let loadedData = SecureData.load(key: "entityData0") {
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let entityData = try decoder.decode([EntityModel].self, from: loadedData)
                entityData.forEach { (EntityModel) in

//Here I Imagine something like this
//var identity: ETIdentity?
//identity = EntityModel.entity
////Here I have the identity, so I can manipulate it like needed, because is from type ETIdentity I can access its methods.
//identity?.getOTP(Date())

                }
            } catch {
                print(error)
            }
        }

引用数据:

GlobalIdentity.swift

struct GlobalIdentity{

    static var identity : ETIdentity?

}

ETidentity.h

@interface ETIdentity : NSObject<NSCoding> {
@private
-(NSString*)getOTP:(NSDate*)time;
@end

编辑 问题是变量 entity (我需要在 ViewController2 中调用它的参数)不是一个字符串,所以它崩溃了,它不起作用。我还尝试将变量标识设置为我需要的类型 var Identity: ETIdentity?,但是 ETIdentity 不在与 Codable 的协议(protocol)中(与结构一起使用,这样我就可以在 ViewController2 中调用它们)

最佳答案

我读了你的问题,发现你缺少的基本事情是你的实体似乎是另一种模型,例如字典或其他类型(如果它是字典),然后执行此操作。目前您的 SecureData.load(key: "entityData0") 包含返回实体模型数组的所有数据,并且您的数据对象 loadedData 必须包含 entity 对象,为什么不尝试像这样为您的 entity 实现 Codable 呢?

struct SortedArryModel: Codable {
var sorterarrkey: String? // if your array contain strings
}

并在您的EntityModel中使用这个SortedAryModel

之后你就可以得到像[key:string]这样的数组,只需将该字符串转换为数组即可。 建议:在你的情况下最好使用 JsonSerialization 而不是 codable,如果你仍然想应用 codable 那么你的元素应该符合 codable 协议(protocol)。就像我上面提到的,将您的实体实现为符合可编码协议(protocol)的模型。

关于swift - 如何使用自定义类型存储和检索变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284761/

相关文章:

Swift 4 Codable解码json

swift - 为什么 swift 同时提供 CGRect 初始化器和 CGRectMake 函数?

ios - Unwind Segue 将我移至错误的 View Controller

ios - 幻灯片菜单(汉堡菜单)iOS Swift

ios - 符合符合 NSObjectProtocol 的协议(protocol),而不从 NSObject 继承?

ios - 显示来自自定义类的 alertController

iOS 如何使用谓词或 KVC 将对象的多个属性转储到字典中?

swift - Codable 类不符合 Decodable 协议(protocol)

ios - 发布 JSON 时出现 JSON 错误

ios - 如何在 iOS 应用程序中获取 Node.js 服务器的响应?