可可&可可触摸。如何从普通 ole 指针创建 NSData 对象?
我在 NSOperation 实例中分配了一大堆数据。我有一个指针:
data = malloc(humungous_amounts_of_god_knows_what);
uint8_t* data;
如何将其打包为 NSData 实例并将其返回到主线程?我假设转换为 NSData 实例后我可以简单地调用:
free(data);
是吗?
另外,回到主线程如何检索指针?
谢谢,
道格
I have malloc'd a whole mess of data in an NSOperation instance. I have a pointer:
data = malloc(humungous_amounts_of_god_knows_what);
uint8_t* data;
How do I package this up as an NSData instance and return it to the main thread? I am assuming that after conversion to an NSData instance I can simply call:
free(data);
Yes?
Also, back on the main thread how do I retrieve the pointer?
Thanks,
Doug
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
-dataWithBytes:length:
或其变体之一:复制字节,然后您可以
free(data)
。要保存副本,假设使用malloc
分配data
使用:您不应该在以下位置的缓冲区上调用
free
在这种情况下,因为NSData
实例将为您释放它。请注意,所有这些方法都会返回一个
autoreleased
实例,因此如果您想在线程之间保留它(并且不使用 GC),您可能必须保留它。您可以使用等效的alloc
/initWithBytes:...
初始化器来代替。要获取指向 NSData 内容的指针,请使用
bytes
。(我想几分钟
NSData
文档将为您提供很好的服务)You want one of the
-dataWithBytes:length:
or its variants:which copies the bytes and you can then
free(data)
. To save a copy, assumingdata
is allocated usingmalloc
use:You should not call
free
on your buffer in this case, as theNSData
instance will free it for you.Note that all of these methods return an
autoreleased
instance, so you will probably have to retain it if you want to keep it around between threads (and aren't using GC). You can use the equivalentalloc
/initWithBytes:...
initializers instead.To get a pointer to an NSData's contents, use
bytes
.(I think a few minutes with the
NSData
documentation will serve you well)谢谢巴里,
我实际上选择了更简单的东西。
在指针周围放置一个 NSValue 包装器:
将其放入字典中以返回到主线程:
回到主线程,当我处理完数据后,我将丢弃它:
干杯,
道格
Thanks Barry,
I actually went with something even simpler.
Put an NSValue wrapper around the pointer:
Stuff it in a dictionary to be returned to the main thread:
Back on the main thread, when I'm done with the data I discard it:
Cheers,
Doug