Episode 5 - Memory Management

Episode 5 - Memory Management

Posted 07/31/2006 - 02:19 by cocoacast

MemoryIn this Podcast we will finish our discussion of Chapter 3 of Cocoa Programming for Mac OS X. The main discussion of this podcast is about memory management. We will briefly review C-style memory management, garbage collection, and reference counting. We also will talk in details about autoreleased objects and memory pools. In addition, we will talk about NSCalendarDate and Custom Initializers. The discussion will be finished with Demos of NSCalendarDate, Custom Initializers, and the Debugger. I will show how to set up a break point in your code and beefy demo the power of the “Fix and Continue” feature of Xcode. In this podcast the first challenge would be discussed, the solution would be posted on the next podcast.

Here are the show notes for this Episode: Show Notes
View the Podcast

Show Notes:

Memory Management (details) &
Introduction to Objective-C cont.
Episode 5
This episode focuses more on memory management & finishes Chapter 3
Chapter 3 - Objective-C
Memory Management (details) &
Introduction to Objective-C cont.
Episode 5
This episode focuses more on memory management & finishes Chapter 3
Chapter 3 - Objective-C

Podcast Announcements

• Podcast grows
• 10 registered users
• Libsyn statistics
• Thanks you !!!

Forum recap

• Requests for topics
• Memory management
• OO - Object Oriented Design
• FAQ Section
• Glossary of Terms (Garbage Collection, etc...)
• Requests for enhancements
• Zoom and Larger text
• Show format
• Skype conferences

Next Steps

• Schedule
• Follow the book chapters
• Take small tangents (as the one today)
• Take BIG tangents when there is enough demand (results from a Poll)
• Let you try to do exercises before posting a solution
• Skype Conferences
• If you are interested, join the first Conference on August 5, 8 a.m. CST
• Post a suggested topic for the talk
• In the future, I’ll try to get access to ARD 3

Recap of the Last Episode

Summary of the Episode 4

Summary of Episode 4

• How to use Xcode to create Command-line application
• Basic Objective-C syntax
• Lottery Application (first crack at it)
• Intro into Memory Management
• Intro into Core Containers (NSArray, NSMutableArray, etc...)

In this Episode

• More detailed Memory Management
• C-style memory management
• Garbage Collection
• Reference Counting
• Autoreleased objects
• Memory Pools
• NSCalendarDate
• Custom Intitializers
• Debugger

More about Memory Management

Autoreleased Objects

C-Style Memory Management

• The Programmer is responsible for Memory Allocation
• Therefore the Programmer is responsible for the cleanup
• Advantages:
• More control over what is allocated and when
• Speed - there is no overhead in memory management
• Disadvantages:
• Control implies responsibility
• Prone to memory leaks (allocated memory that is never released)

Memory Layout

Memory Layout

Memory Allocation and Release in C

Allocation

void * malloc(size_t size);
// Returns a pointer to allocated memory// size_t is generally type definition for unsigned long
Release

void free(void *prt);
// Returns memory pointed by prt into heap pool

Garbage Collection

• Java and C# offer Garage collection
• The idea is the following:
• Allocated whenever you need
• Use as much as you want
• When do not need assign something else (or null if you can)
• We will free memory whenever we feel need to
• The collection happens based on following:
• There are no objects pointing to this memory
• Objects are seasoned (young and old objects)

Garbage Collection - Pros and Cons

• Advantages:
• You do not have to think about memory (well almost)
• Produces Safer Code
• Some functionality in easier to implement (data structures)
• Disadvantages:
• Slow - all threads stop when garbage collection hits
• Overhead in memory management

Reference Counting

• I think of it as a form of Garbage Collection
• User Tells the an object when it is needed by sending a retain
message
• User Tells the the object when it is no longer needed by sending a
release message
• Object counts how many other objects need it by keeping a
retainCount or refCount
• When the count goes to 0, the object is up for deletion
• This is a great link that explains the Memory Management in
Objective-C
http://www.macdevcenter.com/pub/a/mac/excerpt/Cocoa_ch04/index.html

Reference Counting

TrainerOwerGroomretainCount=3Dog

Reference Counting

TrainerOwerGroomretainCount=2Dog

Reference Counting

TrainerOwerGroomretainCount=1Dog

TrainerOwerGroomretainCount=0DogRelease
TrainerOwerGroomretainCount=0DogRelease

Retain and Release

[foo retain];
for (i=0; i<10; i++) {
newNumber = [[NSNumber alloc] initWithInt:(i*3)];
[array addObject:newNumber];
[newNumber release];
}
retain message
release message

Autorelease

- (NSString *)description {
NSString *result;
result=[[NSString alloc] initWithFormat:@”%@ = %d and %d”,
entryDate, firstNumber, secondNumber];
return result;
}
- (NSString *)description {
NSString *result;
result=[[NSString alloc] initWithFormat:@”%@ = %d and %d”,
entryDate, firstNumber, secondNumber];
[result release];
return result;
}

Autorelease

- (NSString *)description {
NSString *result;
result=[[NSString alloc] initWithFormat:@”%@ = %d and %d”,
entryDate, firstNumber, secondNumber];
[result autorelease];
return result;
}

3 Ways to Retain Objects

- (void)setFoo:(NSCalendarDate *)x {
[x retain];
[foo release];
foo = x;
}
- (void)setFoo:(NSCalendarDate *)x {
if(foo !=x){
[foo release];
foo = [x retain];
}
“Retain, then Release”

“Check before change”

3 Ways to Retain Objects (cont.)

- (void)setFoo:(NSCalendarDate *)x {
[foo autorelease];
foo = [x retain];
}
“Autorelease old Value”

Autorelease Pools

• Autorelease Pools enable objects live beyond the scope of the owning
object so that other objects can use it
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
... Code + retained objects that would live until the
release of the pool ...

[pool release];

// All objects retained in this segment would be up for deletion

• Autorelease pools could be nested
• If Nested, the innermost pool is responsible for deallocating objects

Rules of Thumb

• Objects created by alloc, new, copy, or mutableCopy have retain
count of 1 and are not in autorelease pool
• If you get an object by any other method, assume that it has s retain
count of 1 and is in the autorelease pool. If you do not with to be
deallocated with the current autorelease pool, you must retain it
• When you add an object to a collection, it is retained. When you
remove an object from a collection, it is released. Releasing a
collection object (such as an NSArray) releases all objects stored in
it as will
• Make sure that there are as many release or autorelease messages
sent to objects as there are alloc, new, copy, mutableCopy, or retain
messages sent. Code must be balanced

Rules of Thumb (cont.)

• Retain, then release objects in setter methods
• NSString objects created using the @”...” constructs are effectively
constants in the program. Sending retain or release messages to
them has no effect. This explains why we haven’t been releasing the
strings created with the @”...” construct
• This info was obtained from the following URL:
http://www.macdevcenter.com/pub/a/mac/excerpt/Cocoa_ch04/index.html

More Info about Memory Management

http://developer.apple.com/documentation/Cocoa/Conceptual/
MemoryMgmt/Concepts/AutoreleasePools.html
http://www.macdevcenter.com/pub/a/mac/excerpt/Cocoa_ch04/
index.html
http://developer.apple.com/documentation/Cocoa/Conceptual/
MemoryMgmt/index.html

NSCalendarDate

Some basic info about how to get and use date and time in Foundation Framework

NSCalendarDate Class

• NSCalendarDate stores date, time, and timezone
• It inherits from NSDate
• It is immutable
+(id)calendarDate+(id)dateWithYear:month:day:hour:minute:second:timeZone+(id)dateByAddingYear:
months:days:hours:minutes:seconds-(int)dayOfCommonEra-(int)dayOfMonth-(int)dayOfWeek-(int)dayOfYear-(int)minuteOfHour-(int)monthOfYear-(void)setCalendarFormat:(NSString *)format

Custom Initializers

A way to initialize your objects any way you want

Initializers with Arguments

• Initializers can take arguments as any method in Objective-C
• Make sure that the name of custom initializer is descriptive
• Designated initializers
-(id) init; // Default initializers (called by new method)
-(id) initWithEntryDate:(NSCalendarDate *)theDate {
[super init];
[self setEntryDate:theDate];
firstNumber = random() % 100 + 1;
secondNumber = random() % 100 + 1;
return self;
}

-(id) init {
return [self initWithEntryDate:[NSCaledarDate caledarDate]];
}

Demo

NSCalendarDate and Custom Initializers

Demo

Debugger - Break Points, Fix and Continue

Chapter 3 Challenges

The solution will be posted and discussed in the beginning of the next Podcast

Summary

• More detailed Memory Management
• C-style memory management
• Garbage Collection
• Reference Counting
• Autoreleased objects
• Memory Pools
• NSCalendarDate
• Custom Intitializers
• Debugger

Next Time

• Solution to Challenges from Chapter 3
• Chapter 4 Controls
• MVC - Model View Controller
• Beginning of GUI programming
• Target and Action
• Outlets and Actions

Happy Coding Everybody

Trackback URL for this post: http://www.cocoacast.com/?q=trackback/17
0
Your rating: None