Discuss the handling of memory management in Objective-C and Swift, focusing on the differences between Manual Reference Counting (MRC) and Automatic Reference Counting (ARC).
Instruction: Explain the concepts of MRC and ARC as they apply to memory management in iOS development with Objective-C and Swift. Highlight the evolution from MRC to ARC, the benefits of using ARC, and any specific scenarios where manual intervention might still be necessary.
Updated
Official answer
Manual Reference Counting (MRC) in Objective-C makes the programmer balance ownership acquired through operations such as alloc, new, copy, mutableCopy and retain. Release ownership with release or defer that release through autorelease; do not release an object merely because a variable points to it. Incorrect balancing can leak an object or leave a dangling pointer.
With Objective-C ARC, the compiler supplies the ownership operations. Do not explicitly send retain, release or autorelease in ARC-managed code. Swift class instances use ARC as their normal memory-management model; Swift does not offer Objective-C-style MRC as an alternative mode.
ARC does not detect strong cycles. Design delegate and closure ownership deliberately, using weak when the target may disappear or unowned only when its lifetime is guaranteed at use. Confirm that the object actually deinitializes when its work ends.
Two different cases still need explicit attention:
- Core Foundation and raw C resources: follow the API's ownership contract. In Objective-C,
__bridgechanges the pointer type without transferring ownership;__bridge_transfertransfers a retained CF object's ownership to ARC;__bridge_retainedtransfers ownership out and creates a release obligation. These casts apply to compatible bridged types, not arbitrary pointers. Swift imports many annotated CF APIs with automatic management; anUnmanagedresult requires the appropriate retained or unretained operation for that specific API. - Temporary objects in loops: an inner
@autoreleasepoolcan bound autoreleased Objective-C temporaries when measurement shows a peak. It does not break a strong cycle or free objects still owned elsewhere.
Memory management remains an ownership problem under both approaches; ARC automates the bookkeeping, not every resource lifecycle.
Sources
Clang ARC and bridged casts; Apple: working with Core Foundation types in Swift.
Related Questions
-
medium
-
hard
-
hard