Thursday, June 30, 2011

WWDC2011 Session 323 Introducing Automatic Reference Counting

Summary: Automatic Reference Counting (ARC) dramatically simplifies memory management in Objective-C. This session introduces what ARC is, how it is implemented and how to migrate to ARC. Apple asks every developer to move Objective-C code to ARC.

Problems of memory management:

Many (new) developers do not understand reference counting. They don’t know when to retain/release/autorelease. Memory leaks and the app crashes.

What is ARC?

ARC is automatic object memory management. The compiler adds retain/release calls. It still uses reference counting. ARC is not Garbage collection. ARC is compile-time memory management, not run-time memory management.

If we write a stack, our code without ARC will be:

@implementation Stack { NSMutableArray *_array; }

- (id) init {

if (self = [super init])

_array = [[NSMutableArray array] retain];

return self;

}

- (void) push: (id) x {

[_array addObject: x];

}

- (id) pop {

id x = [[_array lastObject] retain];

[_array removeLastObject];

return [x autorelease];

}

- (void) dealloc { [_array release]; [super dealloc]; }

@end

With ARC:

@implementation Stack { NSMutableArray *_array; }

- (id) init {

if (self = [super init])

_array = [NSMutableArray array];

return self;

}

- (void) push: (id) x {

[_array addObject: x];

}

- (id) pop {

id x = [_array lastObject];

[_array removeLastObject];

return x;

}

@end

How do you switch?

WWDC2011 Learning Notes and Index

WWDC2011videos come out before I finish WWDC2010 videos.

It's time to learn WWDC2011 videos. :-)

Index

WWDC2011 Session 323 Introducing Automatic Reference Counting