Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top