Boris
Boris

Reputation: 8931

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?

Upvotes: 1

Views: 1462

Answers (2)

Hampus Nilsson
Hampus Nilsson

Reputation: 6822

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.

Upvotes: 4

jscs
jscs

Reputation: 64002

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.

Upvotes: 3

Related Questions