Search code examples
iosobjective-cnsdata

Remove trailing zeros from NSData


I have an NSData with an arbitrary amount of 0's trailing. I can never be certain of the amount of 0's that are trailing.

How can I trim my NSData object so that only the trailing 0's are removed?


Solution

  • You could get the underlying data as const void * by calling bytes on your NSData object, then walk through the bytes backwards until you find a non-zero byte. Then you could create a new NSData of the new, shorter length by calling subdataWithRange: on your original NSData.