01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

182 CHAPTER 9 Memory management<br />

As an example, the following listing explicitly sends the msg object two additional<br />

retain messages, so three release messages must be sent in order to ensure the object<br />

eventually returns to a retain count of zero.<br />

Listing 9.1<br />

Correctly matching calls to retain and release<br />

NSMutableString *msg =<br />

[[NSMutableString alloc] initWithString:@"Hello, world!"];<br />

[msg retain];<br />

[msg retain];<br />

NSLog(@"The message '%@' has %d characters", msg, [msg length]);<br />

[msg release];<br />

[msg release];<br />

[msg release];<br />

At first glance, the code in listing 9.1 may appear incorrect. The msg object is sent<br />

three release messages, yet there are only two calls to retain. The calls seem unbalanced.<br />

But remember from our previous discussions that a call to alloc (as shown on<br />

the first line) implicitly makes you the owner of the created object. You can consider<br />

alloc as making an internal call to retain on your behalf, and as such, it must be<br />

matched with a call to release.<br />

9.2.3 Determining the current retain count<br />

For diagnostic purposes, it may be desirable to query an object to determine how<br />

many owners it currently has. This can be done by sending it a retainCount message,<br />

as demonstrated by the following listing. This listing is the same as listing 9.1 except<br />

for additional calls to NSLog, which log out the current retain count after each statement<br />

is executed.<br />

Listing 9.2<br />

Querying the retain count of an object during its lifecycle<br />

NSMutableString *msg = [[NSMutableString alloc]<br />

initWithString: @"Hello, world!"];<br />

NSLog(@"After alloc: retain count is %d", [msg retainCount]);<br />

[msg retain];<br />

NSLog(@"After retain: retain count is %d", [msg retainCount]);<br />

NSLog(@"The message '%@' has %d characters", msg, [msg length]);<br />

[msg release];<br />

NSLog(@"After 1st release: retain count is %d", [msg retainCount]);<br />

[msg release];<br />

// NSLog(@"After 2nd release: retain count is %d", [msg retainCount]);<br />

Notice that the log statements report the same values as those manually placed in listing<br />

9.1 and that the last call to NSLog is commented out. This is because the last<br />

release message caused the object to return to a retain count of zero and hence<br />

become deallocated. Once the object is deallocated, it’s impossible to communicate<br />

with it.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!