NSMutableData datawithBytesNoCopy:length:freeWhenDone:似乎使提供给它的缓冲区的副本 [英] NSMutableData datawithBytesNoCopy:length:freeWhenDone: seems to make a copy of the buffer provided to it

查看:626
本文介绍了NSMutableData datawithBytesNoCopy:length:freeWhenDone:似乎使提供给它的缓冲区的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Apple文档,类方法

According to Apple documentation, the class method

+ datawithBytesNoCopy:length:freeWhenDone:

+datawithBytesNoCopy:length:freeWhenDone:

NSData


创建并返回一个数据对象,该数据对象包含给定缓冲区的给定字节数。

Creates and returns a data object that holds a given number of bytes from a given buffer.

NSUInteger len = 1024;
char *buffer = malloc(len);
NSMutableData *data = [NSMutableData dataWithBytesNoCopy:buffer length:len freeWhenDone:YES];
char *dataBytes = data.mutableBytes;
NSLog(@"%@", dataBytes == buffer ? @":D" : @":(");

列印

:(

该方法似乎实际上是一个副本,我预期它不会。
我使用这个错误的方式?
等效的NSData方法按预期工作
如何创建一个NSMutableData对象指向已经存在的缓冲区而不占用任何所有权?

The method seems to actually make a copy, where I expected it not to. Am I using this the wrong way? The equivalent NSData method works as expected. How would I create an NSMutableData object pointing to an already existing buffer without taking any ownership?

推荐答案

毕竟,如果你有一个 NSMutableData 并附加一些更多的数据,那么缓冲区

I would guess that you just can't do what you want to do. After all, if you have an NSMutableData and append some more data to it, then the buffer would need to be reallocated, and no longer use the pointer you supplied.

Apple的二进制数据编程指南说,在 NSMutableData ,无论如何都会复制字节。

Apple's Binary Data Programming Guide says that in the case of NSMutableData, the bytes are copied anyway.

这篇关于NSMutableData datawithBytesNoCopy:length:freeWhenDone:似乎使提供给它的缓冲区的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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