Difference between NSMutableData's mutableBytes and bytes methods
-
24-05-2021 - |
Вопрос
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 aconst void *
. ThemutableBytes
method returns avoid *
. If you want to change the bytes, you need avoid *
with noconst
qualifier. ThemutableBytes
method eliminates the need to cast away theconst
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.
Другие советы
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.