Search code examples
swiftnsdata

how can i modify and reverse every bit in NSData using swift language ?


how can i modify and reverse every bit in NSData using swift language ? i want to make something like code confustion.

//.....
let tempstring : String = "hello world!" 
let tempnsstring : NSString = tempstring as NSString 
var tempnsdata : NSData! 
tempnsdata = tempnsstring.dataUsingEncoding(encoding) 
//.... 

then .. please tell me how to modify the data in NSData ? give me some hint on coding . thanks


Solution

  • NSData is an immutable type, so you cannot modify its content.

    Two alternatives.

    (1) Create a new NSData with modified content.

    let tempstring = "hello world!"
    let encoding = NSUTF8StringEncoding
    let tempnsdata = tempstring.dataUsingEncoding(encoding)!
    
    var tempbytes: [UInt8] = Array(count: tempnsdata.length, repeatedValue: 0)
    
    tempnsdata.getBytes(&tempbytes, length: tempbytes.count)
    
    for i in tempbytes.indices {
        tempbytes[i] = ~tempbytes[i]
    }
    
    let modifiednsdata = NSData(bytes: tempbytes, length: tempbytes.count)
    //Use `modifiednsdata`...
    

    (2) Create a mutable copy and modify the content in it.

    let tempstring = "hello world!"
    let encoding = NSUTF8StringEncoding
    let tempnsdata = tempstring.dataUsingEncoding(encoding)!
    
    let tempnsmutabledata = tempnsdata.mutableCopy() as! NSMutableData
    
    let mutabledataptr = UnsafeMutablePointer<UInt8>(tempnsmutabledata.mutableBytes)
    
    for i in 0..<tempnsmutabledata.length {
        mutabledataptr[i] = ~mutabledataptr[i]
    }
    
    //Use `tempnsmutabledata` as `NSData`