Search code examples
objective-cnsmutabledata

NSMutableData capacity on length change


What happens with NSMutableData initialized with 1Mb capacity if I put 10Mb of data into it and then set length to zero? Does it shrink capacity back to initial value or leaves it as is (10Mb at the moment)?

So basically I need to shrink whole data object to initial capacity and I don't need data inside, but I don't like the idea to re-create object for that, is there any way to achieve that?


Solution

  • The documentation state :

    setLength: Extends or truncates a mutable data object to a given length.

    - (void)setLength:(NSUInteger)length
    

    Parameters length The new length for the receiver.

    Discussion If the mutable data object is extended, the additional bytes are filled with zeros.

    Availability Available in Mac OS X v10.0 and later. See Also – increaseLengthBy: Related Sample Code LSMSmartCategorizer Declared In NSData.h


    So I would go for "truncates" to a 0 size.
    But to be sure you can make a little test and check the heap trace in instrument.