문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top