如何dispatch_data_t转换为NSData的? [英] How to convert dispatch_data_t to NSData?

查看:6351
本文介绍了如何dispatch_data_t转换为NSData的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是正确的方式?

  //转换
常量无效*缓冲区= NULL;
为size_t大小= 0;
dispatch_data_t new_data_file = dispatch_data_create_map(数据,和放大器;缓冲器,与放大器;大小);
如果(new_data_file){/ *避免警告真的 - 因为dispatch_data_create_map要求我们关心回报ARG * /}NSData的*的NSData = [[NSData的页头] initWithBytes:缓冲区长度:大小]。//使用NSData的... code通用删除// 清理
[NSData的释放];
免费(缓冲); //警告:传递常量无效*到void类型的参数*

这是工作的罚款。我最关心的是内存泄漏。泄漏的数据缓冲区是不好玩。所以,是的NSData,缓冲区和dispatch_data_t new_data_file无一不精?

从我可以在<读href=\"http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c\">http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c似乎缓冲区DISPATCH_DATA_DESTRUCTOR_FREE。这是否意味着这是我的责任,以释放缓冲区?


解决方案

在大多数情况下,你的code是正确的。
+ initWithBytes:长度:将复制这样发送缓冲区中,你不必担心数据后释放缓冲区,你可以放心地先释放数据<。 / p>

根据该文件,你没有,你用它做后释放数据:


  

如果您指定buffer_ptr或size_ptr非NULL值,这些​​值在返回
  这些变量只是直到你释放新创建的调度数据有效
  目的。您可以使用这些值作为一个快速的方法来访问新的数据
  数据对象。


您只需松开 new_data_file 变量(ARC不会为你做这个)。

Is this the right way?

// convert
const void *buffer = NULL;
size_t size = 0;
dispatch_data_t new_data_file = dispatch_data_create_map(data, &buffer, &size);
if(new_data_file){ /* to avoid warning really - since dispatch_data_create_map demands we care about the return arg */}

NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];

// use the nsdata... code removed for general purpose

// clean up
[nsdata release];
free(buffer); // warning: passing const void * to parameter of type void *

It is working fine. My main concern is memory leaks. Leaking data buffers is not fun. So is the NSData, the buffer and the dispatch_data_t new_data_file all fine?

From what I can read on http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c it seems the buffer is DISPATCH_DATA_DESTRUCTOR_FREE. Does that mean it is my responsibility to free the buffer?

解决方案

For the most part, your code is correct. +initWithBytes:length: will copy the buffer sent in so, you don't have to worry about freeing the buffer after the data, you can safely free the data first.

According to the documentation, you do NOT free the data after you are done with it:

If you specify non-NULL values for buffer_ptr or size_ptr, the values returned in those variables are valid only until you release the newly created dispatch data object. You can use these values as a quick way to access the data of the new data object.

You simply release the new_data_file variable (ARC will not do this for you).

这篇关于如何dispatch_data_t转换为NSData的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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