手动释放 NSValue
是否可以使用指向 C 结构的指针实例化 NSValue 而无需创建自动释放池?目前,我这样做:
NSValue* val = [NSValue valueWithPointer:(const void*)structure];
但这是由自动释放池释放的。我想控制它并能够在需要时释放它。这可能吗?我尝试过这个:
NSValue* value = [[NSValue alloc] initWithBytes:(const void*)structure objCType:@encode(const void*)];
[value release];
但由于某种原因它崩溃了。还有什么办法可以立即释放吗? 谢谢!
Is it possible to instantiate a NSValue with a pointer to a C structure without having to create a autorelease pool? For the moment, I do this:
NSValue* val = [NSValue valueWithPointer:(const void*)structure];
but this is release by the autorelease pool. I would like to take control of this and be able to dealloc it when I want. Is this possible? I tried this:
NSValue* value = [[NSValue alloc] initWithBytes:(const void*)structure objCType:@encode(const void*)];
[value release];
but it is crashing for some reason. Any other way to be able to release immediately?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该传递一个指向为 objCType: 参数指定的类型的指针。您正在传递类型的变量。因此,例如,如果您想将变量
int foo
存储在 NSValue 中,则可以编写[[NSValue alloc] initWithBytes:&foo objCType:@encode( int)]
。因此,如果要存储指针,则需要将指针作为字节传递给该指针。传递指针本身将导致 NSValue 尝试跟随指针,然后将其指向的字节也视为指针。You're supposed to be passing a pointer to the type that's given for the
objCType:
argument. You're passing a variable of the type. So, for example, if you have a variableint foo
that you want to store in an NSValue, you'd write[[NSValue alloc] initWithBytes:&foo objCType:@encode(int)]
. So if you want to store a pointer, you need to pass a pointer to that pointer as the bytes. Passing the pointer itself will cause NSValue to try to follow the pointer and then treat the bytes that it's pointing to as a pointer as well.