/usr/share/GNUstep/Documentation/Developer/Base/ProgrammingManual/gs-base/Objects.html is in gnustep-base-doc 1.25.1-2ubuntu3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by GNU Texinfo 6.5, http://www.gnu.org/software/texinfo/ -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Objects (Objective-C GNUstep Base Programming Manual)</title>
<meta name="description" content="Objects (Objective-C GNUstep Base Programming Manual)">
<meta name="keywords" content="Objects (Objective-C GNUstep Base Programming Manual)">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<link href="index.html#Top" rel="start" title="Top">
<link href="Make.html#Make" rel="index" title="Make">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="index.html#Top" rel="up" title="Top">
<link href="Classes.html#Classes" rel="next" title="Classes">
<link href="Objective_002dC.html#Objective_002dC" rel="prev" title="Objective-C">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.indentedblock {margin-right: 0em}
blockquote.smallindentedblock {margin-right: 0em; font-size: smaller}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
kbd {font-style: oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nolinebreak {white-space: nowrap}
span.roman {font-family: initial; font-weight: normal}
span.sansserif {font-family: sans-serif; font-weight: normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en">
<a name="Objects"></a>
<div class="header">
<p>
Next: <a href="Classes.html#Classes" accesskey="n" rel="next">Classes</a>, Previous: <a href="Objective_002dC.html#Objective_002dC" accesskey="p" rel="prev">Objective-C</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Working-with-Objects"></a>
<h2 class="chapter">3 Working with Objects</h2>
<a name="index-working-with-objects"></a>
<a name="index-objects_002c-working-with"></a>
<p>Objective-C and GNUstep provide a rich object allocation and memory management
framework. Objective-C affords independent memory allocation and
initialization steps for objects, and GNUstep supports three alternative
schemes for memory management.
</p>
<a name="Initializing-and-Allocating-Objects"></a>
<h3 class="section">3.1 Initializing and Allocating Objects</h3>
<a name="index-objects_002c-initalizing-and-allocating"></a>
<a name="index-allocating-objects"></a>
<p>Unlike most object-oriented languages, Objective-C exposes memory allocation
for objects and initialization as two separate steps. In particular, every
class provides an ’<code>+alloc</code>’ method for creating blank new instances.
However, initialization is carried out by an instance method, not a class
method. By convention, the default initialization method is ’<code>-init</code>’.
The general procedure for obtaining a newly initialized object is thus:
</p>
<div class="example">
<pre class="example">id newObj = [[SomeClass alloc] init];
</pre></div>
<p>Here, the call to <code>alloc</code> returns an uninitialized instance, on which
<code>init</code> is then invoked. (Actually, <code>alloc</code> <i>does</i> set all
instance variable memory to 0, and it initializes the special <code>isa</code>
variable mentioned earlier which points to the object’s class, allowing it to
respond to messages.) The <code>alloc</code> and <code>init</code> calls may be collapsed
for convenience into a single call:
</p>
<div class="example">
<pre class="example">id newObj = [SomeClass new];
</pre></div>
<p>The default implementation of <code>new</code> simply calls <code>alloc</code> and
<code>init</code> as above, however other actions are possible. For example,
<code>new</code> could be overridden to reuse an existing object and just call
<code>init</code> on it (skipping the <code>alloc</code> step). (Technically this kind of
instantiation management can be done inside <code>init</code> as well – it
can deallocate the receiving object and return another one in its place.
However this practice is not recommended; the <code>new</code> method should be
used for this instead since it avoids unnecessary memory allocation for
instances that are not used.)
</p>
<a name="Initialization-with-Arguments"></a>
<h4 class="subsection">3.1.1 Initialization with Arguments</h4>
<p>In many cases you want to initialize an object with some specific information.
For example a <code>Point</code> object might need to be given an <i>x, y</i> position.
In this case the class may define additional initializers, such as:
</p>
<div class="example">
<pre class="example">id pt = [[Point alloc] initWithX: 1.5 Y: 2.0];
</pre></div>
<p>Again, a <code>new</code> method may be defined, though sometimes the word “new”
is not used in the name:
</p>
<div class="example">
<pre class="example">id pt = [Point newWithX: 1.5 Y: 2.0];
// alternative
id pt = [Point pointAtX: 1.5 Y: 2.0];
</pre></div>
<p>In general the convention in Objective-C is to name initializers in a way that
is intuitive for their classes. Initialization is covered in more detail in
<a href="Classes.html#Classes">Instance Initialization</a>. Finally, it is acceptable for an
<code>init...</code> method to return <code>nil</code> at times when insufficient memory
is available or it is passed an invalid argument; for example the argument to
the <code>NSString</code> method <code>initWithContentsOfFile:</code> may be an erroneous
file name.
</p>
<a name="Memory-Allocation-and-Zones"></a>
<h4 class="subsection">3.1.2 Memory Allocation and Zones</h4>
<a name="index-Zones"></a>
<p>Memory allocation for objects in GNUstep supports the ability to specify that
memory is to be taken from a particular region of addressable memory. In the
days that computer RAM was relatively limited, it was important to be able to
ensure that parts of a large application that needed to interact with one
another could be held in working memory at the same time, rather than
swapping back and forth from disk. This could be done by specifying that
particular objects were to be allocated from a particular region of memory,
rather than scattered across all of memory at the whim of the operating
system. The OS would then keep these objects in memory at one time, and swap
them out at the same time, perhaps to make way for a separate portion of the
application that operated mostly independently. (Think of a word processor
that keeps structures for postscript generation for printing separate from
those for managing widgets in the onscreen editor.)
</p>
<p>With the growth of computer RAM and the increasing sophistication of memory
management by operating systems, it is not as important these days to control
the regions where memory is allocated from, however it may be of use in
certain situations. For example, you may wish to save time by allocating
memory in large chunks, then cutting off pieces yourself for object
allocation. If you know you are going to be allocating large numbers of
objects of a certain size, it may pay to create a zone that allocates memory
in multiples of this size. The GNUstep/Objective-C mechanisms supporting
memory allocation are therefore described here.
</p>
<p>The fundamental structure describing a region of memory in GNUstep is called a
<i>Zone</i>, and it is represented by the <code>NSZone</code> struct. All
<code>NSObject</code> methods dealing with the allocation of memory optionally take
an <code>NSZone</code> argument specifying the Zone to get the memory from. For
example, in addition to the fundamental <code>alloc</code> method described above,
there is the <code>allocWithZone:</code> method:
</p>
<div class="example">
<pre class="example">+ (id) alloc;
+ (id) allocWithZone: (NSZone*)zone;
</pre></div>
<p>Both methods will allocate memory to hold an object, however the first one
automatically takes the memory from a default Zone (which is returned by the
<code>NSDefaultMallocZone()</code> function). When it is necessary to group objects
in the same area of memory, or allocate in chunks - perhaps for performance
reasons, you may create a Zone from where you would allocate those objects by
using the <code>NSCreateZone</code> function. This will minimise the paging
required by your application when accessing those objects frequently.
In all normal yuse however, you should confine yourself to the default zone.
</p>
<p>Low level memory allocation is performed by the <code>NSAllocateObject()</code>
function. This is rarely used but available when you require more advanced
control or performance. This function is called by <code>[NSObject
+allocWithZone:]</code>. However, if you call <code>NSAllocateObject()</code> directly to
create an instance of a class you did not write, you may break some
functionality of that class, such as caching of frequently used objects.
</p>
<p>Other <code>NSObject</code> methods besides <code>alloc</code> that may optionally take
Zones include <code>-copy</code> and <code>-mutableCopy</code>. For 95% of cases you
will probably not need to worry about Zones at all; unless performance is
critical, you can just use the methods without zone arguments, that take the
default zone.
</p>
<a name="Memory-Deallocation"></a>
<h4 class="subsection">3.1.3 Memory Deallocation</h4>
<a name="index-memory-deallocation"></a>
<p>Objects should be deallocated from memory when they are no longer needed.
While there are several alternative schemes for managing this process (see
next section), they all eventually resort to calling the <code>NSObject</code>
method <code>-dealloc</code>, which is more or less the opposite of <code>-alloc</code>.
It returns the memory occupied by the object to the Zone from which it was
originally allocated. The <code>NSObject</code> implementation of the method
deallocates only instance variables. Additional allocated, unshared memory
used by the object must be deallocated separately. Other entities that depend
solely on the deallocated receiver, including complete objects, must also be
deallocated separately. Usually this is done by subclasses overriding
<code>-dealloc</code> (see <a href="Classes.html#Classes">Instance Deallocation</a>).
</p>
<p>As with <code>alloc</code>, the underlying implementation utilizes a function
(<code>NSDeallocateObject()</code>) that can be used by your code if you know what
you are doing.
</p>
<a name="Memory-Management"></a>
<h3 class="section">3.2 Memory Management</h3>
<a name="index-memory-management"></a>
<p>In an object-oriented environment, ensuring that all memory is freed when it
is no longer needed can be a challenge. To assist in this regard, there are
three alternative forms of memory management available in Objective-C:
</p>
<ul class="no-bullet">
<li>- Explicit<br>
You allocate objects using <code>alloc</code>, <code>copy</code> etc, and deallocate
them when you have finished with them (using <code>dealloc</code>).
This gives you complete control over memory management, and is highly
efficient, but error prone.
</li><li>- Retain count<br>
You use the OpenStep retain/release mechanism, along with autorelease
pools which provide a degree of automated memory management. This gives
a good degree of control over memory management, but requires some care
in following simple rules. It’s pretty efficient.
</li><li>- Garbage collection<br>
You build the GNUstep base library with garbage collection, and link
with the Boehm GC library … then never bother about
releasing/deallocating memory. This requires a slightly different
approach to programming … you need to take care about what happens
when objects are deallocated … but don’t need to worry about
deallocating them.
</li></ul>
<p>The recommended approach is to use some standard macros defined in
<code>NSObject.h</code> which encapsulate the retain/release/autorelease mechanism,
but which permit efficient use of the garbage collection system if you build
your software with that. We will justify this recommendation after describing
the three alternatives in greater detail.
</p>
<a name="Explicit-Memory-Management"></a>
<h4 class="subsection">3.2.1 Explicit Memory Management</h4>
<a name="index-memory-management_002c-explicit"></a>
<p>This is the standard route to memory management taken in C and C++ programs.
As in standard C when using <code>malloc</code>, or in C++ when using <code>new</code> and
<code>delete</code>, you need to keep track of every object created through an
<code>alloc</code> call and destroy it by use of <code>dealloc</code> when it is no longer
needed. You must make sure to no longer reference deallocated objects;
although messaging them will not cause a segmentation fault as in C/C++, it
will still lead to your program behaving in unintended ways.
</p>
<p>This approach is generally <i>not</i> recommended since the Retain/Release style
of memory management is significantly less leak-prone while still being quite
efficient.
</p>
<a name="OpenStep_002dStyle-_0028Retain_002fRelease_0029-Memory-Management"></a>
<h4 class="subsection">3.2.2 OpenStep-Style (Retain/Release) Memory Management</h4>
<a name="index-memory-management_002c-OpenStep_002dstyle"></a>
<a name="index-memory-management_002c-retain-count"></a>
<p>The standard OpenStep system of memory management employs retain counts.
When an object is created, it has a retain count of 1. When an object
is retained, the retain count is incremented. When it is released the
retain count is decremented, and when the retain count goes to zero the
object gets deallocated.
</p>
<div class="example">
<pre class="example"> Coin *c = [[Coin alloc] initWithValue: 10];
// Put coin in pouch,
[c retain]; // Calls 'retain' method (retain count now 2)
// Remove coin from pouch
[c release]; // Calls 'release' method (retain count now 1)
// Drop in bottomless well
[c release]; // Calls 'release' ... (retain count 0) then 'dealloc'
</pre></div>
<p>One way of thinking about the initial retain count of 1 on the object is that
a call to <code>alloc</code> (or <code>copy</code>) implicitly calls <code>retain</code> as
well. There are a couple of default conventions about how <code>retain</code> and
<code>release</code> are to be used in practice.
</p>
<ul>
<li> <i>If a block of code causes an object to be allocated, it “owns” this
object and is responsible for releasing it. If a block of code merely
receives a created object from elsewhere, it is <b>not</b> responsible for
releasing it.</i>
</li><li> <i>More generally, the total number of <code>retain</code>s in a block should be
matched by an equal number of <code>release</code>s.</i>
</li></ul>
<p>Thus, a typical usage pattern is:
</p>
<div class="example">
<pre class="example"> NSString *msg = [[NSString alloc] initWithString: @"Test message."];
NSLog(msg);
// we created msg with alloc -- release it
[msg release];
</pre></div>
<p>Retain and release must also be used for instance variables that are objects:
</p>
<div class="example">
<pre class="example">- (void)setFoo:(FooClass *newFoo)
{
// first, assert reference to newFoo
[newFoo retain];
// now release reference to foo (do second since maybe newFoo == foo)
[foo release];
// finally make the new assignment; old foo was released and may
// be destroyed if retain count has reached 0
foo = newFoo;
}
</pre></div>
<p>Because of this retain/release management, it is safest to use accessor
methods to set variables even within a class:
</p>
<div class="example">
<pre class="example">- (void)resetFoo
{
FooClass *foo = [[FooClass alloc] init];
[self setFoo: foo];
// since -setFoo just retained, we can and should
// undo the retain done by alloc
[foo release];
}
</pre></div>
<p><b>Exceptions</b>
</p>
<p>In practice, the extra method call overhead should be avoided in performance
critical areas and the instance variable should be set directly. However in
all other cases it has proven less error-prone in practice to consistently use
the accessor.
</p>
<p>There are certain situations in which the rule of having retains and releases
be equal in a block should be violated. For example, the standard
implementation of a container class <code>retain</code>s each object that is added
to it, and <code>release</code>s it when it is removed, in a separate method. In
general you need to be careful in these cases that retains and releases match.
</p>
<a name="Autorelease-Pools"></a>
<h4 class="subsubsection">3.2.2.1 Autorelease Pools</h4>
<p>One important case where the retain/release system has difficulties is when
an object needs to be transferred or handed off to another. You don’t want
to retain the transferred object in the transferring code, but neither do you
want the object to be destroyed before the handoff can take place. The
OpenStep/GNUstep solution to this is the <i>autorelease pool</i>. An
autorelease pool is a special mechanism that will retain objects it is given
for a limited time – always enough for a transfer to take place. This
mechanism is accessed by calling <code>autorelease</code> on an object instead of
<code>release</code>. <code>Autorelease</code> first adds the object to the active
autorelease pool, which retains it, then sends a <code>release</code> to the
object. At some point later on, the pool will send the object a second
<code>release</code> message, but by this time the object will presumably either
have been retained by some other code, or is no longer needed and can thus be
deallocated. For example:
</p>
<div class="example">
<pre class="example">- (NSString *) getStatus
{
NSString *status =
[[NSString alloc] initWithFormat: "Count is %d", [self getCount]];
// set to be released sometime in the future
[status autorelease];
return status;
}
</pre></div>
<p>Any block of code that calls <code>-getStatus</code> can also forego retaining the
return value if it just needs to use it locally. If the return value is to be
stored and used later on however, it should be retained:
</p>
<div class="example">
<pre class="example"> ...
NSString *status = [foo getStatus];
// 'status' is still being retained by the autorelease pool
NSLog(status);
return;
// status will be released automatically later
</pre></div>
<div class="example">
<pre class="example"> ...
currentStatus = [foo getStatus];
// currentStatus is an instance variable; we do not want its value
// to be destroyed when the autorelease pool cleans up, so we
// retain it ourselves
[currentStatus retain];
</pre></div>
<p><b>Convenience Constructors</b>
</p>
<p>A special case of object transfer occurs when a <i>convenience</i> constructor is
called (instead of <code>alloc</code> followed by <code>init</code>) to create an object.
(Convenience constructors are class methods that create a new instance and do
not start with “new”.) In this case, since the convenience method is the
one calling <code>alloc</code>, it is responsible for releasing it, and it does so
by calling <code>autorelease</code> before returning. Thus, if you receive an
object created by any convenience method, it is autoreleased, so you don’t
need to release it if you are just using it temporarily, and you DO need to
retain it if you want to hold onto it for a while.
</p>
<div class="example">
<pre class="example">- (NSString *) getStatus
{
NSString *status =
[NSString stringWithFormat: "Count is %d", [self getCount]];
// 'status' has been autoreleased already
return status;
}
</pre></div>
<p><b>Pool Management</b>
</p>
<p>An autorelease pool is created automatically if you are using the GNUstep
GUI classes, however if you are just using the GNUstep Base classes for a
nongraphical application, you must create and release autorelease pools
yourself:
</p>
<div class="example">
<pre class="example"> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
</pre></div>
<p>Once a pool has been created, any autorelease calls will automatically find
it. To close out a pool, releasing all of its objects, simply release the
pool itself:
</p>
<div class="example">
<pre class="example"> [pool release];
</pre></div>
<p>To achieve finer control over autorelease behavior you may also create
additional pools and release them in a nested manner. Calls to
<code>autorelease</code> will always use the most recently created pool.
</p>
<p>Finally, note that <code>autorelease</code> calls are significantly slower than
plain <code>release</code>. Therefore you should only use them when they are
necessary.
</p>
<a name="Avoiding-Retain-Cycles"></a>
<h4 class="subsubsection">3.2.2.2 Avoiding Retain Cycles</h4>
<p>One difficulty that sometimes occurs with the retain/release system is that
cycles can arise in which, essentially, Object A has retained Object B, and
Object B has also retained Object A. In this situation, neither A nor B will
ever be deallocated, even if they become completely disconnected from the rest
of the program. In practice this type of situation may involve more than two
objects and multiple retain links. The only way to avoid such cycles is to be
careful with your designs. If you notice a situation where a retain cycle
could arise, remove at least one of the links in the chain, but not in such a
way that references to deallocated objects might be mistakenly used.
</p>
<a name="Summary"></a>
<h4 class="subsubsection">3.2.2.3 Summary</h4>
<p>The following summarizes the retain/release-related methods:
</p>
<table>
<tr><td width="25%">Method</td><td width="75%">Description</td></tr>
<tr><td width="25%"><code>-retain</code></td><td width="75%">increases the reference count of an object by 1</td></tr>
<tr><td width="25%"><code>-release</code></td><td width="75%">decreases the reference count of an object by 1</td></tr>
<tr><td width="25%"><code>-autorelease</code></td><td width="75%">decreases the reference count of an object by 1 at some stage in the future</td></tr>
<tr><td width="25%"><code>+alloc</code> and <code>+allocWithZone:</code></td><td width="75%">allocates memory for an object, and returns it with retain count of 1</td></tr>
<tr><td width="25%"><code>-copy</code>, <code>-mutableCopy</code>, <code>copyWithZone:</code> and <code>-mutableCopyWithZone:</code></td><td width="75%">makes a copy of an object, and returns it with retain count of 1</td></tr>
<tr><td width="25%"><code>-init</code> and any method whose name begins with <code>init</code></td><td width="75%">initialises the receiver, returning the retain count unchanged.
<code>-init</code> has had no effect on the reference count.</td></tr>
<tr><td width="25%"><code>-new</code> and any method whose name begins with <code>new</code></td><td width="75%">allocates memory for an object, initialises it, and returns the result.</td></tr>
<tr><td width="25%"><code>-dealloc</code></td><td width="75%">deallocates object immediately (regardless of value of retain count)</td></tr>
<tr><td width="25%">convenience constructors</td><td width="75%">allocate memory for an object, and returns it in an autoreleased state
(retain=1, but will be released automatically at some stage in the future).
These constructors are class methods whose name generally begins with the
name of the class (initial letter converted to lowercase).</td></tr>
</table>
<p>The following are the main conventions you need to remember:
</p>
<ul>
<li> If a unit of code allocates, retains, or copies an object, the same unit,
loosely speaking, is responsible for releasing or autoreleasing it at some
future point. It is best to balance retains and releases within each
individual block of code.
</li><li> If you receive an object, it should remain valid until the object which
provided it is sent another message or until the autorelease pool which
was in use at the point when you received it is emptied. So you can
usually expect it to remain valid for the rest of the current method call
and can even return it as the result of the method.
If you need to store it away for future use (e.g. as an instance variable,
or to use after emptying/destroying an autorelease pool, or to be used
after sending another message to the object’s owner), you must retain it.
</li><li> The retain counts mentioned are guidelines only ... more sophisticated classes
often perform caching and other tricks, so that <code>+alloc</code> methods may
retain an instance from a cache and return it, and <code>-init</code> methods
may release their receiver and return a different object (possibly obtained
by retaining a cached object). In these cases, the retain counts of the
returned objects will obviously differ from the simple examples, but the
ownership rules (how you should use the returned values) remain the same.
</li></ul>
<a name="Garbage-Collection-Based-Memory-Management"></a>
<h4 class="subsection">3.2.3 Garbage Collection Based Memory Management</h4>
<a name="index-memory-management_002c-garbage-collection-based"></a>
<a name="index-garbage-collection"></a>
<p>The GNUstep system can be optionally compiled with a memory sweeping
<b>garbage collection</b> mechanism using the Boehm conservative garbage
collection library (<a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc">http://www.hpl.hp.com/personal/Hans_Boehm/gc</a>).
In this case, you need not worry about retaining and releasing objects; the
garbage collector will automatically track which objects are still referred to
at any given point within the program, and which are not. Those that are not
are automatically deallocated. The situation is largely similar to
programming in Java, except that garbage collection will only be triggered
during memory allocation requests and will be less efficient since pointers
in C are not always explicitly marked.
</p>
<p>Whether in Java or Objective-C, life is still not completely worry-free under
garbage collection however. You still must “help the garbage collector
along” by explicitly dropping references to objects when they become
unneeded. Failing to do this is easier than you might think, and leads to
memory leaks.
</p>
<p>When GNUstep was compiled with garbage collection, the macro flag
<code>GS_WITH_GC</code> will be defined, which you can use in programs to determine
whether you need to call <code>retain</code>, <code>release</code>, etc.. Rather than
doing this manually, however, you may use special macros in place of the
<code>retain</code> and <code>release</code> method calls. These macros call the methods
in question when garbage collection is <i>not</i> available, but do nothing when
it is.
</p>
<table>
<tr><td width="25%">Macro</td><td width="75%">Functionality</td></tr>
<tr><td width="25%"><code>RETAIN(foo);</code></td><td width="75%"><code>[foo retain];</code></td></tr>
<tr><td width="25%"><code>RELEASE(foo);</code></td><td width="75%"><code>[foo release];</code></td></tr>
<tr><td width="25%"><code>AUTORELEASE(foo);</code></td><td width="75%"><code>[foo autorelease];</code></td></tr>
<tr><td width="25%"><code>ASSIGN(foo, bar);</code></td><td width="75%"><code>[bar retain]; [foo release]; foo = bar;</code></td></tr>
<tr><td width="25%"><code>ASSIGNCOPY(foo, bar);</code></td><td width="75%"><code>[foo release]; foo = [bar copy];</code></td></tr>
<tr><td width="25%"><code>DESTROY(foo);</code></td><td width="75%"><code>[foo release]; foo = nil;</code></td></tr>
</table>
<p>In the latter three “convenience” macros, appropriate <code>nil</code> checks are
made so that no retain/release messages are sent to <code>nil</code>.
</p>
<p>Some authorities recommend that you always use the RETAIN/RELEASE macros in
place of the actual method calls, in order to allow running in a non-garbage
collecting GNUstep environment yet also save unneeded method calls in the case
your code runs in a garbage collecting enviromnent. On the other hand, if you
know you are always going to be running in a non-garbage collecting
environment, there is no harm in using the method calls, and if you know you
will always have garbage collection available you can save development effort
by avoiding any use of retain/release or RETAIN/RELEASE.
</p>
<a name="Current-Recommendations"></a>
<h4 class="subsection">3.2.4 Current Recommendations</h4>
<p>As of May 2004 the garbage collection in GNUstep was still considered beta
quality (some bugs exist). In the OS X world, Apple’s Cocoa does <i>not</i>
employ garbage collection, and it is not clear whether there are plans to
implement it. Therefore the majority of GNUstep programmers use the
RETAIN/RELEASE approach to memory management.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Classes.html#Classes" accesskey="n" rel="next">Classes</a>, Previous: <a href="Objective_002dC.html#Objective_002dC" accesskey="p" rel="prev">Objective-C</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Make.html#Make" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|