Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS initializing and returning a new object in a helper method

I'm trying to understand this from a memory management point of view: In one class, I'm making a helper method that will create an NSDictionary object for me.

+(NSDictionary*) getTheDictionary{
    return [[[NSDictionary alloc] initWithObjectsAndKeys:
        @"value", @"key", nil] autorelease];
}

From another class, I use the method.

NSDictionary* theDictionary = [HelperClass getTheDictionary];

Is it enough to just have "autorelease" in the return statement? Do I also need an autorelease on theDictionary?

like image 821
Chicowitz Avatar asked Dec 13 '25 03:12

Chicowitz


1 Answers

getTheDictionary returns an autoreleased object, which means that the object is valid in the calling method, but not owned by the caller. Therefore the calling method must not release or autorelease that object.

It will be released when the current autorelease pool ends, e.g. when program control returns to the main event loop.

like image 116
Martin R Avatar answered Dec 15 '25 15:12

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!