问题
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.
回答1:
There are a couple of reasons why NSMutableData might provide a separate mutableBytes method:
As you suggested in your question, using
mutableBytesmakes it clear to the reader that you want to change the data.The
bytesmethod returns aconst void *. ThemutableBytesmethod returns avoid *. If you want to change the bytes, you need avoid *with noconstqualifier. ThemutableBytesmethod eliminates the need to cast away theconstqualifier.
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.
回答2:
One addition to the rob's answer and his comment:
@Dabbu NSData and NSMutableData store their contents as one contiguous array of bytes.
The thing to keep in mind here is that this behavior was changed in iOS7: now NSData/NSMutableData are not guaranteed to keep contents as one contiguous array. It could be stored as multiple chunks.
So when you call bytes/mutableBytes, they will copy and flatten contents into one contiguous array of bytes, if needed, and then return a pointer to this contiguous chunk.
Depending of what you're trying to do, it may cause an unexpected performance penalty or excessive memory consumption for large buffers.
来源:https://stackoverflow.com/questions/9746944/difference-between-nsmutabledatas-mutablebytes-and-bytes-methods