NSMutableData的mutableBytes和bytes方法之间的区别 [英] Difference between NSMutableData's mutableBytes and bytes methods

查看:465
本文介绍了NSMutableData的mutableBytes和bytes方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个都返回相同的指针。我知道-字节属于 NSData ,为什么 NSMutableData 引入-mutableBytes ?只是为了代码清晰,您访问可变数据时更明显吗?

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]);

谢谢。

推荐答案

NSMutableData 可能提供单独的 mutableBytes 方法有两个原因:

There are a couple of reasons why NSMutableData might provide a separate mutableBytes method:


  • 如您在问题中所建议的,使用 mutableBytes 对读者来说很清楚

bytes 方法返回 const void * mutableBytes 方法返回 void * 。如果要更改字节,则需要 void * 没有 const 限定词。 mutableBytes 方法消除了抛弃 const 限定符的必要。

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.

理论上可能是第三个原因:-[NSData mutableCopy] 方法可能返回 NSMutableData 指向与原始 NSData 相同的缓冲区,并且仅在调用时创建该缓冲区的新可变副本 mutableBytes 。但是,根据我的有限测试,我认为它不是以这种方式实现的。

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.

这篇关于NSMutableData的mutableBytes和bytes方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆