Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Memory Management in Objective C regarding reference count

NOT USING ARC OR AUTOMATIC GARBAGE COLLECTION

     -(Fraction*) add:(Fraction*) f 

     {

          Fraction*result =[[Fraction alloc] init];//To do
return result;

     }

     //after the function returns. What will the reference count  of object that result was pointing to.

     See main.m below.

IN main.m

    int main(int argc,char* argv[])

     {      //To do

          Fraction*ans =[[Fraction alloc] init];    

          ans=[f1 add: f2];

          //I guess that the refrence count of the object that ans will be pointing 

          after this statement will be 1 or 2.//...

     }

An extract regarding this from stephen kochan objective-c

When using manual memory management, this method presents a problem. The result object is alloc’ed and returned from the method after the calculations have been performed. Because the method has to return that object, it can’t release it—that would cause it be destroyed right then and there. Probably the best way to resolve this issue is to autorelease the object so that its value can be returned, with its release delayed until the autorelease pool is drained. You can take advantage of the fact that the autorelease method returns its receiver and embeds it in expressions like this:

Fraction*result =[[[Fraction alloc] init] autorelease];

//or like this: 

return[result autorelease];

iOS 7, reference count

Posted on Sep 22, 2013 8:23 PM

Reply
4 replies

Sep 22, 2013 9:04 PM in response to msuper69

Actually I was concerned with the object, variable result is pointing to in the method add. By this I mean when the function returns, the reference to the object that result was pointing to will be returned and stored in ans. (Will the reference count) of that object will be affected. And also since the function returned we can no longer access the result hence creating a memory leak

Memory Management in Objective C regarding reference count

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.