How do we clear an NSMutableData without using release and then re-alloc/init again to be used again? I was looking at resetBytesInRange to be set at zero but I am unsure of this. Anyone can help?
Asked
Active
Viewed 1.8k times
2 Answers
63
If you want an empty buffer:
[data setLength:0];
If you want to keep its size but set all the bytes to zero:
[data resetBytesInRange:NSMakeRange(0, [data length])];

benzado
- 82,288
- 22
- 110
- 138
-
1What about, [data setData:nil]; ? – karim Mar 11 '13 at 15:14
-
@karim The documentation is ambiguous, but I just tested it, and it works on OS X 10.8. – benzado Mar 11 '13 at 16:16
-
1I see that, if we use second code, the 'data' variable holds always the same memory (but all are deleted - 0000000). Therefore, if we try to append more data to 'data', it will append at the end of this range. For example, my 'data' has 300 bytes, we call this resetBytes, then we add more 100 bytes. The length of 'data' will be 400 bytes (but not 100 bytes). Depend on the strategy, we can use setLength or resetBytesInRange. – Duyen-Hoa Aug 28 '14 at 15:58
0
Swift version of the setting all the bytes to zero:
data.resetBytes(in: NSRange(location:0, length:data.length))

Ales Teska
- 1,198
- 1
- 17
- 38