Difference between dataWithBytesNoCopy and dataWithBytes?

随声附和 提交于 2019-12-03 20:21:23

+ dataWithBytes:length::

Creates and returns a data object containing a given number of bytes copied from a given buffer.

+ dataWithBytesNoCopy:length::

Creates and returns a data object that holds length bytes from the buffer bytes.

dataWithBytes makes a copy of the buffer for the data, while the NoCopy version does not.

Important note: in the discussion section of dataWithBytesNoCopy:length::

The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.

This means that initialising with this method essentially hands ownership of the memory to the NSData object, which will release it with free once it is done. If you try to initialise it with memory that you didn't allocate with malloc, your app will crash when the data object is deallocated.

dataWithBytesNoCopy is useful for when you get the bytes in a buffer from somewhere else, and are ready to hand them over to the NSData object, and won't use them yourself again outside of that.

If you want to initialise the data with memory you manage yourself, use + dataWithBytesNoCopy:length:freeWhenDone:. This is useful if the buffer will be stored somewhere persistently, and not changed or released.

However, if you are not sure how to correctly manage this memory manually, it is better to use dataWithBytes. The other methods are present for performance reasons, as avoiding copying large chunks of data can save a lot of time, but if you aren't sure how to use them, it's probably best not to — an app that doesn't crash is preferable to an app that crashes quickly.

[[NSData alloc] initWithBytes:buffer length:buflength] create a data object containing buflength bytes copied from the buffer bytes.

[NSData dataWithBytesNoCopy:buffer length:buflength] creates a data object that holds buflength bytes from the buffer bytes. The returned object takes ownership of the buffer pointer and frees it on deallocation. Therefore, buffer must point to a memory block allocated with malloc.

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