Search code examples
objective-ccocoansmutabledata

Filling NSMutableData with bytes results in zero length


When setting up NSMutableData like this:

NSMutableData* mRgb = [NSMutableData dataWithCapacity:3];
((char*)[mRgb mutableBytes])[0] = 10;
((char*)[mRgb mutableBytes])[1] = 90;
((char*)[mRgb mutableBytes])[2] = 160;

I have the problem that the length is still 0:

int len = [mRgb length]; // Is 0!

Why is that so?


Solution

  • dataWithCapacity just reserves that many bytes in memory, it does not mean the data is that size yet.

    An example of this would be when receiving an image from the internet. Up front you do not know how large the image will be, so just create a Data object with capacity for 1MB, that way you do not continually need to resize the data as you receive more of it.

    What you want to use is the dataWithLength method, which creates a data objects containing that many bytes from the start. Or you can call setLength:N to change how much of the data is in use.