Does NSValue free its value when freed?

╄→尐↘猪︶ㄣ 提交于 2021-01-28 06:33:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!