mercredi 13 janvier 2016

How to encode and decode struct to NSData in swift?

I have the following struct definition:

struct ThreadManager: Equatable {
  let fid: Int
  let date: NSDate
  let forumName: String
  let typeid: Int
  var page: Int
  var threadList: [Thread]
  var totalPageNumber: Int?
}

and the thread is :

  struct Thread: Equatable {
    let author: Author
    let replyCount: Int
    let readCount: Int
    let title: String
    let tid: Int
    let isTopThread: Bool
    var attributedStringDictionary: [String: NSAttributedString]
    var postDescripiontTimeString: String
    var hasRead: Bool
}

How can I encode a ThreadManager variable to NSData? I tried to used the following functions, but it does not worK.

func encode<T>(var value: T) -> NSData {
  return withUnsafePointer(&value) { p in
    NSData(bytes: p, length: sizeofValue(value))
  }
}

func decode<T>(data: NSData) -> T {
  let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T))
  data.getBytes(pointer, length: sizeof(T))

  return pointer.move()
}

I have ThreadManager items, and I want to store them into sqlite. So I need to convert them to NSData. I have a variable called threadManager, the number of items in its threadList is about 70. I run the code and set a breakpoint, and input encode(threadManager) in xcode console, it is only 73bytes. It is wrong. How can I encode and decode those struct to NSData.

Aucun commentaire:

Enregistrer un commentaire