자주 사용하는 Swift 자료형 변환
  • NSInteger -> NSData (IntToNSData)
var src:NSInteger = 100
let data = NSData(bytes:&src, length:sizeof(NSInteger))
  • NSData -> NSInteger (NSDataToInt)
var src:NSInteger = 100
var out:NSInteger = 0
let data = NSData(bytes:&src, length:sizeof(NSInteger))
data.getBytes(&out, length:sizeof(NSInteger))
  • String -> NSData (StringToNSData)
let textString : String = "abcd"
let textData : NSData = textString.dataUsingEncoding(NSUTF8StringEncoding)!
  • NSData -> String (NSDataToString)
let textString : String = "abcd"
let textData : NSData = textString.dataUsingEncoding(NSUTF8StringEncoding)!
let dataString : String = NSString(data: textData, encoding: NSUTF8StringEncoding)!
  • User Class  -> NSData  / NSData -> User Class
class UserClass: NSObject ,NSCoding {
    var name:String!
    override init(){
        self.name = nil
        super.init()
    }
    required init(coder aDecoder: NSCoder) {
        super.init()
        self.name = aDecoder.decodeObjectForKey("name") as String?
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
    }
} 
// User Class -> NSData 
var userClassInstance : UserClass = UserClass()
var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(userClassInstance)

// NSData -> User Class 
var userClass : UserClass = NSKeyedUnarchiver.unarchiveObjectWithData(data) as UserClass


저작자 표시 비영리 변경 금지
신고
Posted by 까칠코더.


티스토리 툴바