Download iPhone Game Development

Transcript
Just like the this keyword in C++ and Java, the self keyword is available
inside Objective-C class methods.
Memory Management
Since Objective-C is a superset of C, all of the rules regarding malloc and free still apply.
On the iPhone, there is no Garbage Collector that takes care of all objects for you, like
the one in Java does, so it is possible to have memory leaks if allocated memory is not
properly deallocated.
However, Objective-C does implement a reference counter inside the base class
NSObject. Therefore, any class that inherits from NSObject (and most will) has the same
reference counting functionality built-in. Specifically, the copy, new, retain, release,
autorelease, and alloc methods provided by NSObject are what get the job done.
Whenever an NSObject subclass instance is created using the alloc method or any
function with new or copy at the beginning of its name, it will be created with a reference
count of 1. You can use the retain function to increment the value by one, and the
release and autorelease functions to decrement the value by one. Once the reference
value has reached 0, the object will be removed from memory.
If you call retain on an object, you will leak memory if you do not also call release or
autorelease on that object because the reference count will never reach 0.
Constructors and Destructors
Like C++, Objective-C classes support the concept of constructor and destructor functions, but with some slight variation. When an object is allocated, the programmer
must call the initialization function manually. By default, initialization functions are
named init.
The following code is typical of Objective-C:
Animal* beaver = [[Animal alloc] init];
When an Objective-C class is destroyed from memory, its dealloc function will be
called, similar to a destructor. If you overload the dealloc function in your class, you
must also call the dealloc method of the superclass or it may leak memory:
-(void) dealloc {
//perform destructor code here
[super dealloc];
}
Objective-C Primer | 33