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 releas开发者_Go百科e immediately? Thanks!
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 variable int 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.
NSValue* val = [NSValue valueWithPointer:(const void*)structure];
[val retain];
精彩评论