home Memory management in Objective-C   

Memory management of Objective C objects is done via reference counting.

Methods:
  alloc               - allocs memory for the object, returns pointer to it, sets refcount to 1
  release            - decrease refcount, sends dealloc if refcount is 0
  retain              - inc refcount
  copy               - returns a copy of the object with refcount 1
  autorelease      - add object to current autorelease pool. Later pool will send release method to the object
  retainCount     - returns refcount

Allocation and free:

NSString *s = [[NSString alloc] initWithString: @"hello"];
[s release];

Function that returns allocated object must use autorelease pool because the method doesn't own the memory but can't 

-(NSString *) returnAllocatedString {
  NSString * str = [[NSString alloc] initWithString: @"test"];
  return [str autorelease];
}

Autorelease pool schedules release messages for later:
* only one at a time (current autorelease pool)
* created automatically by NSApplication object (create manually if not using NSApplication)
* when receives release message, calls release on its objects
* NSApplication sends release at the end of event loop iteration
* can create autorelease pools with smaller scope (per method, in a scope) for performance and memory size (so that global pool doesn't grow too big)

← newer • 146 of 636older →