4

I am new to Swift and iOS Development. How do we clear an NSMutableData without using release and then re-alloc/init again to be used again?

I have tried resetBytesInRange() but that replaces the contents by zero.

I tried data.length = 0, but there is garbage data at the end after appending.

data.setData(nil) gives an error.

I read this question but it doesn't solve my problem on swift.

Please help.

Community
  • 1
  • 1
saurabh
  • 6,687
  • 7
  • 42
  • 63
  • 4
    `data.length = 0` *does* clear the contents of the NSData object. Can you show a concrete example where this does not work? – Martin R Dec 04 '14 at 07:45

2 Answers2

4

Try using setData() with NSData():

mytableData.setData(NSData())
Eimantas
  • 48,927
  • 17
  • 132
  • 168
-1

For Swift create new data object for current data will replace old bytes with empty bytes.

data = NSData(data: NSData())
println(data)

For mutable data:

mutableData = NSMutableData(data: NSMutableData())
println(mutableData)

Output: Empty bytes array

<>
Kampai
  • 22,848
  • 21
  • 95
  • 95
  • The question is about mutating `NSMutableData`. – Kirsteins Dec 04 '14 at 07:31
  • `mutableData = NSMutableData(data: NSMutableData())` replaces the `NSMutableData`. This might not be the behaviour if you have multiple references to this `NSMutableData`. – Kirsteins Dec 04 '14 at 07:47
  • OP wants `nil NSMutableData` that will also affect multiple references. – Kampai Dec 04 '14 at 07:50
  • @Kirsteins: What you think this for down vote? Where you find this will make multiple references. Give me an explanation. – Kampai Dec 04 '14 at 07:53
  • If you have multiple references pointing to the same object as variable `data` and you assign new object to `data` the other references will point to different object. In your case you are not mutating, but replacing. – Kirsteins Dec 04 '14 at 07:56