3

Please clarify, how to deal with returned objects from methods?

Below, I get employee details from GeEmployeetData function with autorelease,

  1. Do I have to retain the returned object in Process method?
  2. Can I release *emp in Process function?

    -(void) Process { Employee *emp = [self GeEmployeetData] }

    +(Employee*) GeEmployeetData{

    Employee *emp = [[Employee alloc]init]; //fill entity

    return [emp autorelease]; }

1 Answer 1

4

99% of the time you should retain autoreleased objects returned from other methods if you want to keep them around.

With autoreleased objects, when the pool is drained, the objects in the pool get sent the release message. That is why 99% of the time you will want to retain autoreleased objects, because the chances of you getting an object with a retainCount of more than 1 is highly unlikely.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, is the below code correct? I am retaining the returned object and releasing the local emp object. (void) Process { Employee *emp = [[self GeEmployeetData] retain] [emp release]; } +(Employee) GeEmployeetData{ Employee *emp = [[Employee alloc]init]; //fill entity return [emp autorelease]; }
You should never care about retain counts because Cocoa may make any number of optimisations under the hood. All you need to worry about is when to retain and when to release/autorelease. Also, the pool works by sending release to each object that it holds, which is not necessarily equivalent to decrementing its retain count, as some objects are "unreleasable" and sending release is a noop.
this will do it: Employee *emp = [[self GeEmployeetData] retain ]; //do stuff... [emp release ]; } +(Employee*) GeEmployeetData{ return [[[Employee alloc]init] autorelease]; }
@geeth You should also think about defining an initializer that returns an autoreleased object like this: + ( Employee *) employee { return [ [ [ Employee alloc ] init ] autorelease ]; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.