2

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.

Ivan Dossev
  • 565
  • 5
  • 11

2 Answers2

3

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Just to add slightly to @rob's answer, the `- bytes` method is readonly, **even when called from NSMutableData**. Is is part of the base class, however if you are using NSMutableData and want a mutable copy of the bytes, you call the `- mutableBytes` function so that you can make changes to it (which is what mutable means). – lnafziger Mar 17 '12 at 03:45
  • Anyone know the internals of NSMutableData data management? Does the `- mutableBytes` pointer have all the data exactly in one row, or does it segment the data in chunks of for example 1kb and at the end of each segment is a pointer to the next 1kb segment? (I hope that made sense). – Ivan Dossev Mar 20 '12 at 19:17
  • 2
    @Dabbu `NSData` and `NSMutableData` store their contents as one contiguous array of bytes. – rob mayoff Mar 20 '12 at 19:28
0

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.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129