| name | Objective-C ARC Patterns |
| user-invocable | false |
| description | Use when automatic Reference Counting in Objective-C including strong/weak references, retain cycles, ownership qualifiers, bridging with Core Foundation, and patterns for memory-safe code without manual retain/release. |
| allowed-tools | [] |
Objective-C ARC Patterns
Introduction
Automatic Reference Counting (ARC) is Objective-C's memory management system
that automatically inserts retain and release calls at compile time. ARC
eliminates most manual memory management while providing deterministic memory
behavior and preventing common memory bugs like use-after-free and double-free.
Unlike garbage collection, ARC provides immediate deallocation when reference
counts reach zero, making it suitable for resource-constrained environments like
iOS. Understanding ARC's ownership rules, qualifiers, and patterns is essential
for writing memory-safe Objective-C code and avoiding retain cycles.
This skill covers strong and weak references, ownership qualifiers, retain
cycles, Core Foundation bridging, and best practices for ARC-based memory
management.
Strong and Weak References
Strong references maintain ownership of objects and prevent deallocation, while
weak references observe objects without preventing deallocation.
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSArray *friends;
@property (nonatomic, strong) UIImage *photo;
@end
@implementation Person
@end
@interface ViewController : UIViewController
@property (nonatomic, weak) id<ViewControllerDelegate> delegate;
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@end
@implementation ViewController
@end
@protocol ViewControllerDelegate <NSObject>
- (void)viewControllerDidFinish:(ViewController *)controller;
@end
void strongWeakExample(void) {
Person *person = [[Person alloc] init];
person.name = @"Alice";
__weak Person *weakPerson = person;
NSLog(@"Weak person: %@", weakPerson.name);
person = nil;
NSLog(@"After nil: %@", weakPerson);
}
@interface NodeOld : NSObject
@property (nonatomic, unsafe_unretained) NodeOld *parent;
@property (nonatomic, strong) NSArray<NodeOld *> *children;
@end
@implementation NodeOld
@end
@interface CommentOld : NSObject
@property (nonatomic, strong) NSString *text;
@property (nonatomic, weak) PostOld *post;
@end
@interface PostOld : NSObject
@property (nonatomic, strong) NSArray<CommentOld *> *comments;
@end
@implementation CommentOld
@end
@implementation PostOld
@end
void blockCaptureExample(void) {
Person *person = [[Person alloc] init];
person.name = @"Bob";
void (^strongBlock)(void) = ^{
NSLog(@"%@", person.name);
};
__weak Person *weakPerson = person;
void (^weakBlock)(void) = ^{
NSLog(@"%@", weakPerson.name);
};
strongBlock();
weakBlock();
}
Strong references increment retain count, while weak references are
automatically set to nil when the object deallocates, preventing dangling
pointers.
Retain Cycles and Breaking Them
Retain cycles occur when objects hold strong references to each other, preventing
deallocation. Breaking cycles requires weak or unowned references.
@interface Parent : NSObject
@property (nonatomic, strong) NSArray<Child *> *children;
@end
@interface Child : NSObject
@property (nonatomic, weak) Parent *parent;
@property (nonatomic, strong) NSString *name;
@end
@implementation Parent
- (void)dealloc {
NSLog(@"Parent deallocated");
}
@end
@implementation Child
- (void)dealloc {
NSLog(@"Child deallocated");
}
@end
void noCycleExample(void) {
Parent *parent = [[Parent alloc] init];
Child *child = [[Child alloc] init];
child.name = @"Alice";
child.parent = parent;
parent.children = @[child];
}
@protocol DataSourceDelegate <NSObject>
- (void)dataSourceDidUpdate:(id)source;
(, ) <DataSourceDelegate> delegate;
- ()fetchData;
- ()fetchData {
[.delegate dataSourceDidUpdate:];
}
- ()dealloc {
();
}
(, ) *baseURL;
- ()fetchDataWithCompletion:( (^)( *data))completion;
- ()fetchDataWithCompletion:( (^)( *))completion {
(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{
*data = [ dataUsingEncoding:];
(dispatch_get_main_queue(), ^{
completion(data);
});
});
}
- ()dealloc {
();
}
(, ) NetworkManager *networkManager;
- ()loadData {
__ () weakSelf = ;
[.networkManager fetchDataWithCompletion:^( *data) {
__ (weakSelf) strongSelf = weakSelf;
(!strongSelf) ;
(, strongSelf.view);
}];
}
- ()dealloc {
();
}
(, ) *observers;
- ()addObserver:()observer;
- ()removeObserver:()observer;
- ()notifyObservers;
- ()init {
= [ init];
() {
_observers = [ array];
}
;
}
- ()addObserver:()observer {
[.observers addObject:[ valueWithPointer:(__bridge *)observer]];
}
- ()removeObserver:()observer {
[.observers removeObject:[ valueWithPointer:(__bridge *)observer]];
}
- ()notifyObservers {
( *value .observers) {
observer = (__bridge )( *)[value pointerValue];
(observer) {
}
}
}
Always use weak references for delegates, parent pointers, and observers to
break retain cycles. Use the weak-strong dance in blocks for safe self access.
Ownership Qualifiers
ARC provides ownership qualifiers that explicitly control memory management
behavior for variables and properties.
@interface Container : NSObject
@property (nonatomic, strong) id strongProperty;
@property (nonatomic, weak) id weakProperty;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSArray *items;
@property (nonatomic, assign) NSInteger count;
@property (nonatomic, assign) CGFloat value;
@property (nonatomic, unsafe_unretained) id unsafeProperty;
@end
@implementation Container
@end
void qualifierExamples(void) {
__strong NSString *strongString = @"Hello";
__ *weakString = strongString;
__ *unsafeString = strongString;
* __autoreleasing error;
}
(, ) *text;
(, ) *recipients;
copyPropertyExample() {
Message *message = [[Message alloc] init];
*mutableText = [ stringWithString:];
message.text = mutableText;
[mutableText appendString:];
(, message.text);
(, mutableText);
}
loadData( **outData, **outError) {
(outData) {
*outData = [ dataUsingEncoding:];
}
;
}
autoreleaseExample() {
*data;
*error;
(loadData(&data, &error)) {
(, data);
} {
(, error);
}
}
(, , ) *identifier;
(, , ) *name;
(, , ) <> delegate;
(, , ) *items;
Choose copy for properties that accept mutable types like NSMutableString or
NSMutableArray to prevent unexpected mutations.
Core Foundation Bridging
Core Foundation objects require explicit memory management and bridging to work
correctly with ARC-managed Objective-C objects.
void bridgingExample(void) {
NSString *nsString = @"Hello";
CFStringRef cfString = (__bridge CFStringRef)nsString;
NSString *nsString2 = (__bridge NSString *)cfString;
}
void bridgeRetainExample(void) {
NSString *nsString = @"Hello";
CFStringRef cfString = (__bridge_retained CFStringRef)nsString;
CFIndex length = CFStringGetLength(cfString);
NSLog(@"Length: %ld", (long)length);
CFRelease(cfString);
}
void bridgeTransferExample(void) {
CFMutableStringRef cfString = CFStringCreateMutable(NULL, 0);
CFStringAppend(cfString, CFSTR("Hello"));
NSMutableString *nsString = (__bridge_transfer NSMutableString *)cfString;
[nsString appendString:];
(, nsString);
}
cfCollectionExample() {
cfArray = (
,
( *[]){, , },
,
&kCFTypeArrayCallBacks
);
*nsArray = (__bridge_transfer *)cfArray;
(, nsArray);
}
cfPropertyListExample() {
*dict = @{: };
plist = (__bridge_retained )dict;
url = (__bridge )[ fileURLWithPath:];
(plist, url, kCFPropertyListXMLFormat_v1_0, , );
(plist);
}
myCFArrayApplierFunction( *value, *context) {
*string = (__bridge *)value;
(, string);
}
cfCallbackExample() {
cfArray = (__bridge )@[, , ];
(
cfArray,
(, (cfArray)),
myCFArrayApplierFunction,
);
}
Use __bridge for temporary bridging, __bridge_retained when transferring to
CF, and __bridge_transfer when transferring from CF to ARC.
ARC and C Structures
When mixing ARC objects with C structures, explicit memory management is
required for object pointers in structures.
typedef struct {
__unsafe_unretained NSString *name;
NSInteger age;
} PersonStruct;
void structExample(void) {
PersonStruct person;
person.name = @"Alice";
person.age = 30;
NSLog(@"Person: %@, %ld", person.name, (long)person.age);
}
@interface PersonData : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation PersonData
@end
typedef struct PersonStructManual {
CFStringRef name;
NSInteger age;
} PersonStructManual;
PersonStructManual createPerson(NSString *name, NSInteger age) {
PersonStructManual person;
person.name = CFBridgingRetain(name);
person.age = age;
return person;
}
void releasePerson(PersonStructManual person) {
CFRelease(person.name);
}
manualStructExample() {
PersonStructManual person = createPerson(, );
releasePerson(person);
}
{
__ *items;
count;
} ContainerStruct;
{
*items;
count;
} ContainerStructPointer;
pointerStructExample() {
*array = @[@, @, @];
ContainerStructPointer container;
container.items = (__bridge *)array;
container.count = array.count;
*retrieved = (__bridge *)container.items;
(, retrieved);
}
Avoid storing ARC-managed objects in C structures. Use Objective-C classes or
CF types with manual management instead.
Autorelease Pools
Autorelease pools manage temporary objects created by convenience methods and
prevent memory buildup in loops.
int main(int argc, char *argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([AppDelegate class]));
}
}
void processLargeDataset(void) {
NSArray *items = ;
for (id item in items) {
@autoreleasepool {
NSString *processed = [item description];
NSData *data = [processed dataUsingEncoding:NSUTF8StringEncoding];
}
}
}
void inefficientLoop(void) {
for (NSInteger i = 0; i < 1000000; i++) {
NSString *string = [NSString stringWithFormat:@"Number %ld", (long)i];
}
}
void efficientLoop(void) {
for (NSInteger i = 0; i < 1000000; i++) {
@autoreleasepool {
*string = [ stringWithFormat:, ()i];
}
}
}
nestedPools() {
{
*outer = ;
{
*inner = [ stringWithFormat:, outer];
}
}
}
backgroundWork() {
(dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{
{
*result = [ stringWithFormat:];
(, result);
}
});
}
Use explicit autorelease pools in tight loops that create many temporary objects
to prevent memory growth between autorelease pool drains.
Best Practices
-
Use weak for delegates and parent references to break retain cycles in
common delegation and hierarchical patterns
-
Apply weak-strong dance in blocks when capturing self to prevent cycles
while ensuring safe access during execution
-
Choose copy for mutable type properties like NSString and NSArray to
prevent unexpected mutations by callers
-
Annotate nullability explicitly with nullable/nonnull to improve API
clarity and Swift interoperability
-
Use autorelease pools in loops that create temporary objects to prevent
memory buildup in long-running iterations
-
Bridge CF types explicitly with appropriate qualifiers to manage
ownership transfer between ARC and manual reference counting
-
Avoid storing objects in C structs as ARC cannot manage them; use
Objective-C classes or CF types instead
-
Check for nil after weak references as they can become nil at any time
when the referenced object deallocates
-
Use NSPointerArray for weak collections when maintaining collections of
observers or delegates to prevent cycles
-
Profile with Instruments to detect retain cycles, memory leaks, and
excessive autoreleased object creation
Common Pitfalls
-
Creating retain cycles with strong delegates causes memory leaks; always
use weak for delegate properties
-
Capturing self strongly in blocks without weak creates cycles when blocks
are stored in properties
-
Forgetting strong reference in weak-strong dance allows self to
deallocate during block execution
-
Using strong for parent pointers creates bidirectional strong references
and prevents deallocation
-
Not using copy for NSString properties allows callers to pass mutable
strings and modify them later
-
Bridging CF types incorrectly causes over-releases or leaks depending on
ownership transfer direction
-
Storing ARC objects in C structures leads to premature deallocation or
crashes as ARC cannot track them
-
Creating NSTimer without invalidation retains target strongly and
prevents deallocation until invalidated
-
Missing autorelease pools in tight loops causes memory growth and
potential crashes from memory pressure
-
Using unsafe_unretained instead of weak creates dangling pointers that
crash when accessed after deallocation
When to Use This Skill
Use ARC patterns when writing Objective-C code for iOS, macOS, watchOS, or tvOS
to ensure memory-safe applications without manual retain/release calls.
Apply weak references and the weak-strong dance when implementing delegates,
observers, or callbacks that could create retain cycles.
Employ proper bridging when interfacing with Core Foundation, Core Graphics, or
other C-based frameworks that use manual reference counting.
Leverage autorelease pools when processing large datasets, importing data, or
performing other operations that create many temporary objects in loops.
Use appropriate ownership qualifiers when designing public APIs to clearly
communicate memory management expectations to clients.
Resources