问题
Have a look at this pseudocode:
void* magicpointer = malloc(OVER_NINE_THOUSAND);
NSValue* v = [NSValue valueWithPointer:magicpointer];
[v release];
When v is released, does magicpointer get freed as well, or do I have to do that manually? I am using manual reference counting.
回答1:
It doesn't get freed - NSValue is just a wrapper so you can treat arbitrary values as objects. It doesn't do anything with the wrapped pointer.
回答2:
No, NSValue
won't.
Sounds like you might want to use NSData
, it can free it's pointer when it's released:
void* magicpointer = malloc(OVER_NINE_THOUSAND); NSData *d = [NSData dataWithBytesNoCopy:magicpointer length:OVER_NINE_THOUSAND freeWhenDone:YES]; //d is autoreleased, so no need to -release it.
回答3:
NSValue does not free the pointer when the NSValue is released. The only thing the documentation says about the pointer stored in an NSValue is:
If you create an NSValue object with an allocated data item, don’t deallocate its memory while the NSValue object exists.
The main reason for using an NSValue is to box a value so that it can be placed into an NSArray or similar collection which only accept objects. It wouldn't make sense for the memory to be freed simply because the NSValue box is no longer needed.
来源:https://stackoverflow.com/questions/10136114/does-nsvalue-free-its-value-when-freed