Question

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?

Was it helpful?

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.

OTHER TIPS

dataWithCapacity: "...doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed..."

Use dataWithLength:, which allocates and zeroes the requested amount.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top