axiom-objc-block-retain-cycles

charleswiltgen/axiom · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/charleswiltgen/axiom --skill axiom-objc-block-retain-cycles
0 commentsdiscussion
summary

Block retain cycles are the #1 cause of Objective-C memory leaks. When a block captures self and is stored on that same object (directly or indirectly through an operation/request), you create a circular reference: self → block → self. Core principle 90% of block memory leaks stem from missing or incorrectly applied weak-strong patterns, not genuine Apple framework bugs.

skill.md

Objective-C Block Retain Cycles

Overview

Block retain cycles are the #1 cause of Objective-C memory leaks. When a block captures self and is stored on that same object (directly or indirectly through an operation/request), you create a circular reference: self → block → self. Core principle 90% of block memory leaks stem from missing or incorrectly applied weak-strong patterns, not genuine Apple framework bugs.

Red Flags — Suspect Block Retain Cycle

If you see ANY of these, suspect a block retain cycle, not something else:

  • Memory grows steadily over time during normal app use
  • UIViewController instances not deallocating (verified in Instruments)
  • Crash: "Sending message to deallocated instance" from network/async callback
  • Network requests or animations prevent view controller from closing
  • Weak reference becomes nil unexpectedly in a block
  • NSLog, NSAssert, or string formatting hiding self references
  • Completion handler fires after the view controller "should be gone"
  • FORBIDDEN Rationalizing as "It's probably normal memory usage"
    • Memory leaks are never "normal"
    • Apps should return to baseline memory after user dismisses a screen
    • Do not rationalize this as "good enough" or "monitor it later"

Critical distinction Block retain cycles accumulate silently. A single cycle might be 100KB, but after 50 screens viewed, you have 5MB of dead memory. MANDATORY: Test on real device (oldest supported model) after fixes, not just simulator.

Mandatory First Steps

ALWAYS run these FIRST (before changing code):

// 1. Identify the leak with Allocations instrument
// In Xcode: Xcode > Open Developer Tool > Instruments
// Choose Allocations template
// Perform an action (open/close a screen with the suspected block)
// Check if memory doesn't return to baseline
// Record: "Memory baseline: X MB, after action: Y MB, still allocated: Z objects"

// 2. Use Memory Debugger to trace the cycle
// Run app, pause at suspected code location
// Debug > Debug Memory Graph
// Search for the view controller that should be deallocated
// Right-click > Show memory graph
// Look for arrows pointing back to self (the cycle)
// Record: "ViewController retained by: [operation/block/property]"

// 3. Check if block is assigned to self or self's properties
// Search for: setBlock:, completion:, handler:, callback:
// Check: Is the block stored in self.property?
// Check: Is the block passed to something that retains it (network operation)?
// Record: "Block assigned to: [property or operation]"

// 4. Search for self references in the block
// Look for: [self method], self.property, self-> access
// Look for HIDDEN self references:
//   - NSLog(@"Value: %@", self.property)
//   - NSAssert(self.isValid, @"message")
//   - Format strings: @"Name: %@", self.name
// Record: "self references found in block: [list]"

// Example output:
// Memory not returning to baseline ✓
// ViewController retained by: AFHTTPRequestOperation
// Operation retains: successBlock
// Block references self: [self updateUI], NSLog with self.property
// → DIAGNOSIS: Block retain cycle confirmed

What this tells you

  • Memory stays high → Leak confirmed, not false alarm
  • ViewController retained by operation → Block is the culprit
  • Block references self → Pattern: weak-strong needed
  • Hidden self in NSLog/NSAssert → Need to check ALL macro calls
  • No self references found → Maybe not a block cycle, investigate elsewhere

MANDATORY INTERPRETATION

Before changing ANY code, you must confirm ONE of these:

  1. If memory doesn't return to baseline AND ViewController still allocated → Block retain cycle exists
  2. If memory returns to baseline → Not a retain cycle, investigate other causes
  3. If cycle exists but you can't find self references → Check for hidden references (macros, indirect property access)
  4. If you find the cycle but don't understand the chain → Trace backward through retained objects in Memory Graph

If diagnostics are contradictory or unclear

  • STOP. Do NOT proceed to patterns yet
  • Add more diagnostics: Print the object graph, list retained objects
  • Ask: "If memory is low, why is the ViewController still allocated?"
  • Run Instruments > Leaks instrument if memory graph is confusing

Decision Tree

Block memory leak suspected?
├─ Memory stays high after dismiss?
│  ├─ YES
│  │  ├─ ViewController still allocated in Memory Graph?
│  │  │  ├─ YES → Proceed to patterns
│  │  │  └─ NO → Not a block cycle, check other leaks
│  │  └─ NO → Not a leak, normal memory usage
│  │
│  └─ Crash: "Sending message to deallocated instance"?
│     ├─ Happens in block/callback?
│     │  ├─ YES → Block captured weakSelf but it became nil
│     │  │  └─ Apply Pattern 4 (Guard condition is wrong or missing)
│     │  └─ NO → Different crash, not block-related
│     └─ Crash is timing-dependent (only on device)?
│        └─ YES → Weak reference timing issue, apply Pattern 2
├─ Block assigned to self or self.property?
│  ├─ YES → Apply Pattern 1 (weak-strong mandatory)
│  ├─ Assigned through network operation/timer/animation?
│  │  └─ YES → Apply Pattern 1 (operation retains block indirectly)
│  └─ Block called immediately (inline execution)?
│     ├─ YES → Optional to use weak-strong (no cycle possible)
│     │  └─ But recommend for consistency with other blocks
│     └─ NO → Block stored or passed to async method → Use Pattern 1
├─ Multiple nested blocks?
│  └─ YES → Apply Pattern 3 (must guard ALL nested blocks)
├─ Block contains NSAssert, NSLog, or string format with self?
│  └─ YES → Apply Pattern 2 (macro hides self reference)
└─ Implemented weak-strong pattern but still leaking?
   ├─ Check: Is weakSelf used EVERYWHERE?
   ├─ Check: No direct `self` references mixed in?
   ├─ Check: Nested blocks also guarded?
   └─ Check: No __unsafe_unretained used?

Common Patterns

Pattern Selection Rules (MANDATORY)

Apply ONE pattern at a time, in this order

  1. Always start with Pattern 1 (Weak-Strong Basics)

    • If block assigned to self or self's properties → Pattern 1
    • If block passed to operation/request that retains it → Pattern 1
    • Only proceed to Pattern 2 if pattern still leaks
  2. Then Pattern 2 (Hidden self in Macros)

    • Only if memory still leaks after applying Pattern 1
    • Check for NSAssert, NSLog, string formatting
    • If found, apply Pattern 2
  3. Then Pattern 3 (Nested Blocks)

    • Only if block has nested callbacks
    • Each nested block needs its own guard
    • If found, apply Pattern 3
  4. Then Pattern 4 (Guard Condition Edge Cases)

    • Only if crash happens with weakSelf approach
    • Check guard condition is correct
    • Verify strongSelf used everywhere

FORBIDDEN

  • ❌ Applying multiple patterns at once
  • ❌ Skipping Pattern 1 because "I already know weak-strong"
  • ❌ Using __unsafe_unretained as workaround
  • ❌ Using strong self "just this once"
  • ❌ Rationalizing: "The block is too small for a leak"

Pattern 1: Weak-Strong Pattern (MANDATORY)

PRINCIPLE Any block that captures self must use weak-strong pattern if block is retained by self (directly or transitively).

❌ WRONG (Creates retain cycle)

[self.networkManager GET:@"url" success:^(id response) {
    self.data = response;  // self is retained by block
    [self updateUI];       // block is retained by operation
} failure:^(NSError *error) {
    [self handleError:error];  // CYCLE!
}];

✅ CORRECT (Breaks the cycle)

__weak typeof(self) weakSelf = self;
[self.networkManager GET:@"url" success:^(id response) {
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        strongSelf.data = response;
        [strongSelf updateUI];
    }
} failure:^(NSError *error) {
    __weak typeof(self) weakSelf2 = self;
    typeof(self) strongSelf = weakSelf2;
    if (strongSelf) {
        [strongSelf handleError:error];
    }
}];

Why this works

  1. __weak typeof(self) weakSelf = self; creates a weak reference outside the block
  2. Block captures weakSelf (weak reference), not self (strong reference)
  3. When block executes, convert to strongSelf (temporary strong ref)
  4. Check if strongSelf is nil (object was deallocated)
  5. Use strongSelf for the duration of the block
  6. strongSelf released when block exits → No cycle

Important details

  • Declare weakSelf OUTSIDE the block, not inside
  • Use typeof(self) for type safety (works in both ARC and non-ARC)
  • Guard condition MUST use if (strongSelf), not just declare it
  • Never use direct self inside the block once weakSelf is declared
  • Apply to EVERY block that captures self
  • ANY block that captures self must use weak-strong pattern
    • This includes: [self method], self.property, self->ivar
    • Property access (self.property = value) captures self just like method calls
  • Blocks passed to frameworks:
    • If framework documentation says 'block is called asynchronously' → Use weak-strong pattern (framework retains the block)
    • If framework documentation says 'block is called immediately' → Still safe to use weak-strong (better practice)
    • If unsure about framework behavior → Always use weak-strong (doesn't hurt)

Capturing variables (avoiding indirect self references)

// ✅ SAFE: Capture simple values extracted from self
__weak typeof(self) weakSelf = self;
[self.manager fetch:^(id response) {
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        NSString *name = strongSelf.name;  // Extract value
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Name: %@", name);  // Captured the STRING, not self
        });
    }
}];

// ❌ WRONG: Capture properties directly in nested blocks
__weak typeof(self) weakSelf = self;
[self.manager fetch:^(id response) {
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Name: %@", strongSelf.name);  // Captures strongSelf again!
        });
    }
}];

When nesting blocks, extract simple values first, then pass them to the inner block. This avoids creating an indirect capture of self through property access.

Time cost 30 seconds per block


Pattern 2: Hidden self in Macros

how to use axiom-objc-block-retain-cycles

How to use axiom-objc-block-retain-cycles on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add axiom-objc-block-retain-cycles
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/charleswiltgen/axiom --skill axiom-objc-block-retain-cycles

The skills CLI fetches axiom-objc-block-retain-cycles from GitHub repository charleswiltgen/axiom and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/axiom-objc-block-retain-cycles

Reload or restart Cursor to activate axiom-objc-block-retain-cycles. Access the skill through slash commands (e.g., /axiom-objc-block-retain-cycles) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.430 reviews
  • Chaitanya Patil· Dec 16, 2024

    Solid pick for teams standardizing on skills: axiom-objc-block-retain-cycles is focused, and the summary matches what you get after install.

  • Kwame Ramirez· Dec 8, 2024

    Keeps context tight: axiom-objc-block-retain-cycles is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Yusuf Chawla· Nov 27, 2024

    Registry listing for axiom-objc-block-retain-cycles matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Piyush G· Nov 7, 2024

    We added axiom-objc-block-retain-cycles from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Rahul Santra· Nov 3, 2024

    I recommend axiom-objc-block-retain-cycles for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Shikha Mishra· Oct 26, 2024

    axiom-objc-block-retain-cycles fits our agent workflows well — practical, well scoped, and easy to wire into existing repos.

  • Pratham Ware· Oct 22, 2024

    Useful defaults in axiom-objc-block-retain-cycles — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Layla Gill· Oct 18, 2024

    axiom-objc-block-retain-cycles reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Olivia Tandon· Sep 9, 2024

    axiom-objc-block-retain-cycles has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Li Perez· Aug 28, 2024

    Solid pick for teams standardizing on skills: axiom-objc-block-retain-cycles is focused, and the summary matches what you get after install.

showing 1-10 of 30

1 / 3