In Objective-C, pointers manage memory by referencing addresses. A pointer variable stores an address, its value is that address, and the memory unit value is the data at that address. By default, pointers are strong, marked with the strong keyword. Weak pointers are declared using __weak, such as __weak Person *p;.
Automatic Reference Counting (ARC) is a compiler feature introduced with LLVM 3.0, eliminating the need for manual memory management by automatical inserting retain, release, and autorelease calls. Developers avoid writing these keywords, relying on the compiler to handle memory correctly. Unlike garbage collection, ARC operates at compile time, not runtime. Manual Reference Counting (MRC) refers to the older, manual approach.
ARC determines object deallocation based on strong pointer references: a object is released when no strong pointers point to it, disregarding traditional reference counters.
To check if ARC is enabled in a project (default in iOS 5+), verify that "Objective-C Automatic Reference Counting" is set to YES in build settings. Key indicators include prohibitions on calling release, autorelease, and using [super dealloc] in overridden dealloc methods.
In single-object memory management with ARC, objects are released immediately when no strong pointers reference them. For example:
Vehicle *vehicle = [[Vehicle alloc] init];
vehicle = nil; // Memory is freed as no strong pointer remains
vehicle.speed = 20; // No error; sending messages to nil is safe
Strong pointers are default or explicitly marked with __strong. Weak pointers use __weak:
__weak Vehicle *weakVehicle = vehicle; // Weak reference
weakVehicle = nil; // Does not deallocate memory
For multiple objects, ARC prevents retain cycles by using weak pointers in one direction. In @property declarations, parameters adjust memory semantics:
strong: For Objective-C objects, similar to MRC'sretain.weak: For Objective-C objects, analogous toassign, avoiding strong references.assign: For primitive data types.copy: Typically forNSStringtypes. To resolve cyclic references, pairstrongwithweakin properties.
ARC features include disallowing calls to release, retain, and retainCount, allowing dealloc overrides without [super dealloc], and using strong/weak in properties for object types and assign for non-object types. Weak pointers are automatically set to nil when their referenced object deallocates. Avoid initializing weak pointers with newly allocated objects, as they release immediately.
To mix ARC and non-ARC code, use compiler flags: -fno-objc-arc for non-ARC files and -fobjc-arc for ARC conversion. Always backup files before converting MRC to ARC.