discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Releasing objects declared in method?


From: Frederic De Jaeger
Subject: Re: Releasing objects declared in method?
Date: 10 May 2003 19:18:49 +0200
User-agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.2

Albert>     Questions:
Albert> 1. Do I need to release tmpObject *explicitly*?
Albert> 2. If I need to release it, when and how?
Albert> 3. If I need to release it before the method ends, does it mean that I
Albert> can't use "return [tmpObject count]" statement?

Albert>     Thanks for your reply. 

There are some rules about memory management inside OpenStep.  There
are very few of them but I find it hard to clearly  express them.  I'm
gonna try:

* You are never supposed to "release" an object, except in some
  particular situations (but they occur very often,  thus you *MUST* know
  them perfectly)

  The particular cases are :
      - If you previously "retain" the object (I'm assuming you know
        what it means)
      - If you got the object by sending a message (to another object),
        whose name starts     with "alloc..."  or "new...".  Most of (All?)
        the time, the other object is a class.

  Some examples:

{
  NSMutableArray *obj = [[NSMutableArray alloc] initWithCapacity: 10];
  /* The name starts with alloc, I must release it after I'm finished
     with it*/
  ...
  RELEASE(obj);
}


{
  NSMutableArray *obj = [NSMutableArray array];

  /* The name doesn't start with alloc or new, I'm not responsible for
     releasing it.
  */
  ...
}

The last case is a little bit magical and you must understand what is 
happening here.  Of course, the class returns a fresh object for me to
play with.  Therefore, some memory has been allocated by the class
when I called [NSMutableArray array].  But if I don't release the
object, how will it be deallocated? 
The answer is simple: the object is put in a "pool" by the
NSMutableArray class.  And the pool will release it "later".  If
you're playing with the gui, "later" means "when the control flow will
return to the main loop".  Anyway, it will be after the end of the
current method, and that what really matters.
 
As Pete told you, your code is wrong.  They are other rules, that are
not directly related to memory management.

* You should call "init..." *ONLY* on objects you just allocated with a
  message such as "alloc..." 

(for information,  "[c new...]" is always a short-hand 
for "[[c alloc] init...]")

If you get an object by ANY other way, you can be sure it is already
"init"ed 

For information:


    tmpObject = [NSMutableArray arrayWithCapacity: 8];

is equivalent to

    tmpObject = [[NSMutableArray alloc] initWithCapacity: 8];
    AUTORELEASE(tmpObject);

Thus in fact,  "initWithCapacity" was already sent to tmpObject.

Cheers,

  Frederic




reply via email to

[Prev in Thread] Current Thread [Next in Thread]