2016-12-28 53 views
2

我想定義一個C++結構作爲swift代碼並序列化並反序列化它以寫入套接字。ios swift,如何將'object to nsdata'

class PacketHeader: NSObject, NSCoding { 
    var ver: UInt8 = 0 
    var len: UInt32 = 0 

    required init(coder aDecoder: NSCoder) { 
     ?? 
    } 

    func encode(with aCoder: NSCoder) { 
     ?? 
    } 
} 

我找不到函數來解碼和編碼uint8,uint32。

+0

你爲什麼不使用它作爲對象?我的意思是說把它轉換成NSNumber,檢查它。有選項也打開func decodeInt32(forKey鍵:字符串) - > Int32 open func decodeInt64(forKey key:String) - > Int64 – karthikeyan

回答

1

的Xcode 8(SWIFT 3)遊樂場:

class PacketHeader: NSObject, NSCoding { 
    var ver: UInt8 = 0 
    var len: UInt32 = 0 

    override init() { 
     super.init() 
    } 

    required init(coder aDecoder: NSCoder) { 

     if let ver = aDecoder.decodeObject(forKey: "ver") as? NSNumber { 
      self.ver = ver.uint8Value 
     } 

     if let len = aDecoder.decodeObject(forKey: "len") as? NSNumber { 
      self.len = len.uint32Value 
     } 

    } 

    func encode(with aCoder: NSCoder) { 
     aCoder.encode(NSNumber(value: ver), forKey: "ver") 
     aCoder.encode(NSNumber(value: len), forKey: "len") 
    } 

} 

let data = PacketHeader() 
data.ver = 10 
data.len = 8 

let savedData = NSKeyedArchiver.archivedData(withRootObject: data) 
let obj = NSKeyedUnarchiver.unarchiveObject(with: savedData) as? PacketHeader 
obj?.ver 
obj?.len 
1

這裏就是你需要做什麼,如果你不想轉換爲NSNumber,雖然我懷疑這一定是一個重複的問題:

class PacketHeader: NSObject, NSCoding { 
    var ver: UInt8 = 0 
    var len: UInt32 = 0 

    init(ver: UInt8, len: UInt32) { 
     self.ver = ver 
     self.len = len 
     super.init() 
    } 

    required init(coder aDecoder: NSCoder) { 
     self.ver = UInt8(aDecoder.decodeCInt(forKey: "ver")) 
     self.len = UInt32(aDecoder.decodeCInt(forKey: "len")) 
    } 

    func encode(with aCoder: NSCoder) { 
     aCoder.encodeCInt(Int32(self.ver), forKey: "ver") 
     aCoder.encodeCInt(Int32(self.len), forKey: "len") 
    } 
} 

let x = PacketHeader(ver: 75, len: 123) 
let e = NSKeyedArchiver.archivedData(withRootObject: x) 
if let y = NSKeyedUnarchiver.unarchiveObject(with: e) as? PacketHeader { 
    print("\(y.ver), \(y.len)") // 75, 123 
} else { 
    print("URK???") 
}