Difference between NSMutableData's mutableBytes and bytes methods

耗尽温柔 提交于 2019-12-24 02:25:09

问题


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 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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!