Both return the same pointer. I know - bytes
belongs to NSData
, why does NSMutableData
introduce - mutableBytes
? Is it just for code clarity so it is more obvious you are accessing mutable data? Does it really matter which one is used?
NSMutableData* mydata = [[NSMutableData alloc] init];
[mydata appendData: [@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%p", [mydata mutableBytes]);
NSLog(@"%p", [mydata bytes]);
Thanks.
There are a couple of reasons why NSMutableData
might provide a separate mutableBytes
method:
As you suggested in your question, using mutableBytes
makes it clear to the reader that you want to change the data.
The bytes
method returns a const void *
. The mutableBytes
method returns a void *
. If you want to change the bytes, you need a void *
with no const
qualifier. The mutableBytes
method eliminates the need to cast away the const
qualifier.
In theory there could be a third reason: the -[NSData mutableCopy]
method could return an NSMutableData
that points to the same buffer as the original NSData
, and only create a new, mutable copy of the buffer when you call mutableBytes
. However, I don't think it's implemented this way based on my very limited testing.