In Objective C how do I explicitly release an object owned by another object? Or perhaps equivalently inform the owning object that it does not own the child object anymore. Consider the following:
- (void) testWithNSString:(NSString *)val
{
NSData *data = [val dataUsingEncoding:NSASCIIStringEncoding];
// ...
// now I want to explicitly release data e.g. due to low memory
}
In [val dataUsingEncoding:NSASCIIStringEncoding] an NSData object is returned and I assume (due to general conventions of ownership) that it will be released, when val is released. This seems acceptable from a non-leaking perspective. But this strategy raises two issues:
- What if I want to explicitly release
dataobject immediately e.g. due to low memory? - What if I do not want the caller of
testWithNSStringto be left with anNSString valobject (after thetestWithNSStringhas returned), which suddently has ownership of new objects?
This is incorrect.
dataUsingEncodingwill create a newNSDataobject that has no relationship withval(as to lifetime). It is anautoreleasedobject and it will be released at the next cycle of the run loop (approx, we don’t know exactly), unless you retain it somehow.If you want the object to be released immediately, and you are using ARC, you can simply assign nil to its pointer:
If you are not using ARC, your best option is to wait for the run loop autorelease pool to do its job. Or you can create a local autorelease pool in your method, so that autoreleased objects are drained at the end of the method and not at the next run loop cycle. This will make a difference only in case of long-running methods (or chain of methods), so I don’t know if it would make sense in your case.
As I said,
valhas no ownership ofdata.Summing this all up, your
dataobject is autoreleased and it will be pretty soon after your method ends (unless it is a long-running method); sodatamemory will be recovered in an efficient way and I would not worry about it (unless it is a long-running method, as I said).