Black Mamba

Faster, Higher, Stronger.

Reference Count Style Memory Management and ARC Rules

Reference Count Style Memory Management

  • A variable hold the objects generate by itself
1
id obj = [[NSObject alloc] init];
  • A variable can hold the objects generate by other variables
1
2
id obj = [NSMutableArray array];
[obj retain];
  • If the objects of a variable are no longer needed, the variable can release the objects held by itself
1
2
3
4
5
6
7
8
// Generate by itself and hold the objects by itself
id obj = [[NSObject alloc] init];
[obj release];

// Generate by others and hold the objects by itself
id obj = [NSMutableArray array];
[obj retain];
[obj release];
  • A variable cannot release the objects held by others
1
2
id obj1 = [obj0 object];
[obj1 release];    // error

ARC Rules

  • Can’t use retain / release / retainCount / autorelease

    • Memory management is the compiler’s job, so there is no need to use this methods
    • This methods is need to use when the ARC is invalid
  • Can’t use NSAllocateObject / NSDeallocateObject

    • When ARC is available, the methods NSAllocateObject and NSDeallocateObject are both forbidden
  • Don’t call dealloc explicitly

    • When the object is abandoned, dealloc is called automatically no matter ARC is available or not
  • Using @autoreleasepool instead of using NSAutoreleasePool

  • Object type variables can’t be a member of structure

    • Structure can’t manage the life circle of its member

Bonus: The Diffence Between Objective-C Objects and Core Foundation Objects

  • Objective-C objects are generated by Foundation Framework
  • Core foundation objects are generated by Core Foundation Framework

Comments