Search code examples
objective-cnsautoreleasepool

Objective-C autoreleasepool directive effect variables outside scope.


Let's say I've got c++ function combined with objective-c members. The function gets std::string and convert it to NSstring*, and work with this variable before leaving...

Should i expect the NSstring* to be released at the end of autoreleasepool scope ?

void myclass::myfunc(context& ctx)
{ 
    @autoreleasepool
    {
        std::string path = ctx.getData().path;
        NSString *nsPath = [NSString stringWithUTF8String:path.c_str()];
        ... (do something with nsString, Should it be released after leaving the scope ?)
    }
}

Solution

  • No you don't need to. According to the rule you only need release the variable if you are increasing its retain count in one of the following ways:

    1. Initializing via new or alloc/init.
    2. Copying via copy.
    3. Increasing the retain count via retain.

    If you are getting a variable by any means but the above-mentioned ways, you don't own it, and hence you don't need to release it.

    The string returned via [NSString stringWithUTF8String:path.c_str()] is autoreleased string. It will be released once the current runloop finishes. So you don't need to release it.