Modular iOS development automation suite. 8 workflow-specific MCP servers (400-3500 tokens) with 24 tools across Xcode, Simulator, and IDB. Enable only what you need!

version
0.4.0
GitHub stars
187

Install

/plugin install xclaude-plugin@xclaude-plugin-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add conorluddy/xclaude-plugin.

Contents

Discovered from source

Skills 8

Accessibility Testing Skill

WCAG compliance and accessibility quality assurance for iOS applications

Overview

This skill teaches accessibility-first testing strategies for iOS apps. Accessibility testing ensures apps are usable by everyone, including people with disabilities. It combines automated validation of accessibility metadata with manual verification of user experience patterns.

Why accessibility testing matters:

  • Legal compliance: WCAG 2.1 is required in many jurisdictions
  • User reach: 15% of population has some form of disability
  • Better UX: Accessible apps are better for everyone
  • SEO benefits: Better structure improves discoverability
  • Cost savings: Fix issues early vs. retrofitting

When to Use This Skill

Use this skill when:

  1. Validating accessibility compliance before release
  2. Debugging VoiceOver issues or user reports
  3. Implementing new features that need accessibility support
  4. Running accessibility audits as part of CI/CD
  5. Testing Dynamic Type support and contrast ratios
  6. Verifying semantic markup and element roles
  7. Checking keyboard navigation and focus management

This skill covers:

  • Accessibility tree analysis and interpretation
  • WCAG 2.1 compliance checking (A, AA, AAA levels)
  • VoiceOver testing patterns
  • Dynamic Type validation
  • Common accessibility violations and fixes

Quick Reference

TaskTool/OperationTypical Time
Check accessibility qualityaccessibility-quality-check~80ms
Query full accessibility treeidb-ui-describe~120ms
Find element by labelidb-ui-find-element~100ms
Screenshot (fallback only)screenshot~2000ms
VoiceOver simulationManual testing-

Core Principle: Accessibility Tree First

The accessibility tree IS your primary testing interface.

Unlike visual testing (screenshots), the accessibility tree reveals:

  • What screen readers "see"
  • Semantic structure and relationships
  • Focus order and navigation paths
  • Element roles and states
  • Text alternatives for non-text content

3-4x faster and more reliable than visual inspection.

Key Concepts

WCAG 2.1 Levels

Level A (Minimum):

  • Text alternatives for images
  • Keyboard accessibility
  • No color-only information
  • Headings and labels present

Level AA (Recommended):

  • Contrast ratio 4.5:1 for normal text
  • Contrast ratio 3:1 for large text
  • Resize text up to 200%
  • Meaningful focus order
  • Descriptive labels and instructions

Level AAA (Enhanced):

  • Contrast ratio 7:1 for normal text
  • Contrast ratio 4.5:1 for large text
  • No timing requirements
  • Comprehensive error handling

Target Level AA for most apps.

iOS Accessibility Properties

Essential Properties:

  1. accessibilityLabel: What element is

    • Example: "Profile photo", "Send message button"
    • Should be concise, descriptive
  2. accessibilityValue: Current state/value

    • Example: "50%", "Selected", "3 of 10"
  3. accessibilityHint: What happens when activated

    • Example: "Opens your profile settings"
    • Use sparingly, only when action isn't obvious
  4. accessibilityTraits: Element behavior

    • Button, Link, Header, Selected, etc.
  5. isAccessibilityElement: Should be exposed

    • true for interactive/informative elements
    • false for decorative elements

Accessibility Tree vs Visual UI

Accessibility tree is semantic, not visual:

Visual UI:
┌─────────────────┐
│ [img] John Doe  │  ← Visual: Image + Text
│ Online          │
└─────────────────┘

Accessibility Tree:
• Button: "John Doe, Online, Profile"  ← Single focusable element
  - label: "John Doe"
  - value: "Online"
  - hint: "Opens profile"
  - traits: [Button]

Good accessibility = logical semantic structure.

Standard Workflow

1. Initial Accessibility Quality Check

Start here to assess app's accessibility implementation:

{
  "operation": "check-accessibility",
  "target": "booted"
}

Interprets accessibility tree quality:

  • "excellent": 90%+ elements have labels, good semantic structure
  • "good": 70-90% coverage, minor issues
  • "fair": 50-70% coverage, needs improvement
  • "poor": <50% coverage, serious accessibility problems
  • "insufficient": Cannot perform accessibility-based testing

Decision tree:

excellent/good → Proceed with accessibility-first testing
fair           → Test but expect to find issues
poor           → Major remediation needed
insufficient   → App may not support assistive tech

Note: Most modern iOS apps score "good" or "excellent".

2. Query Accessibility Tree

Core operation for all accessibility testing:

{
  "operation": "describe",
  "target": "booted",
  "parameters": {
    "operation": "all"
  }
}

Returns complete accessibility tree:

{
  "elements": [
    {
      "label": "Login",
      "type": "Button",
      "frame": { "x": 100, "y": 400, "width": 175, "height": 50 },
      "enabled": true,
      "visible": true,
      "traits": ["Button"],
      "value": null,
      "hint": "Sign in to your account"
    },
    {
      "label": "Email address",
      "type": "TextField",
      "value": "",
      "frame": { "x": 50, "y": 300, "width": 275, "height": 44 },
      "enabled": true,
      "visible": true,
      "traits": ["TextField"]
    }
  ]
}

Analyze for:

  • All interactive elements have labels
  • Labels are descriptive and concise
  • Proper element types/traits
  • Logical reading order (top-to-bottom, left-to-right)
  • No duplicate or confusing labels

3. Validate Specific Elements

Find and verify accessibility of specific UI elements:

{
  "operation": "find-element",
  "target": "booted",
  "parameters": {
    "query": "Submit button"
  }
}

Validates:

  • Element exists in accessibility tree
  • Has appropriate label
  • Correct type and traits
  • Enabled/visible state correct

4. Test Navigation and Focus

Verify logical focus order:

  1. Query accessibility tree
  2. Check elements appear in logical order
  3. No gaps in navigation
  4. Focus lands on meaningful elements first

Focus order issues:

Bad:  [Button: Cancel] → [Image: Decorative] → [Button: Submit] → [TextField]
Good: [TextField] → [Button: Submit] → [Button: Cancel]

WCAG Compliance Workflows

Testing Checklist

1. Text Alternatives (WCAG 1.1)

All non-text content needs text alternative:

Query accessibility tree for all images
For each image:
  ✓ Has accessibilityLabel
  ✓ Label describes image content
  ✓ Or marked as decorative (isAccessibilityElement: false)

Common violations:

  • Images with no label
  • Generic labels: "image", "icon", "photo"
  • Labels don't describe content: "png_12345"

Fix:

// Bad
imageView.isAccessibilityElement = true // No label

// Good
imageView.isAccessibilityElement = true
imageView.accessibilityLabel = "Profile photo of John Doe"

// Decorative (best if truly decorative)
imageView.isAccessibilityElement = false
2. Keyboard/Focus Navigation (WCAG 2.1)

All functionality available via sequential navigation:

Query accessibility tree
Verify elements appear in logical order:
  ✓ Top to bottom
  ✓ Left to right
  ✓ Grouped logically
  ✓ Interactive elements are focusable
  ✓ Decorative elements are not focusable

Test pattern:

1. describe → Get all elements
2. Map order: element[0], element[1], element[2]...
3. Verify order matches visual/logical flow
4. Check no important elements missing
3. Contrast Ratios (WCAG 1.4.3)

Minimum contrast requirements:

  • Normal text (<18pt): 4.5:1 ratio (AA), 7:1 ratio (AAA)
  • Large text (≥18pt or ≥14pt bold): 3:1 ratio (AA), 4.5:1 (AAA)
  • UI components: 3:1 ratio (AA)

Testing approach:

1. screenshot → Capture current screen
2. Use color picker to sample text/background
3. Calculate contrast ratio: (L1 + 0.05) / (L2 + 0.05)
4. Verify meets WCAG AA (4.5:1 or 3:1)

Common violations:

  • Gray text on white: 2.5:1 (fails)
  • Light blue on white: 2.8:1 (fails)
  • Dark gray on white: 4.6:1 (passes AA)

Note: Screenshots are appropriate for contrast testing (color-based).

4. Labels and Instructions (WCAG 3.3.2)

All inputs have clear labels:

Query accessibility tree
For each TextField/input element:
  ✓ Has accessibilityLabel
  ✓ Label describes purpose
  ✓ Label visible or programmatically associated
  ✓ Required fields indicated
  ✓ Format instructions provided if needed

Good labels:

{
  "type": "TextField",
  "label": "Email address",
  "hint": "Enter your email to sign in",
  "value": ""
}

Bad labels:

{
  "type": "TextField",
  "label": "TextField",  // Generic
  "value": ""
}
5. Dynamic Type Support (iOS-specific)

Text scales from 100% to 200%:

Test pattern:

1. Set Dynamic Type to smallest size
2. Launch app, screenshot, verify readable
3. Set Dynamic Type to largest size
4. Launch app, screenshot, verify:
   ✓ Text scales appropriately
   ✓ No text truncation
   ✓ Layout adapts
   ✓ Buttons still tappable

Settings locations:

  • Settings → Accessibility → Display & Text Size → Larger Text
  • Simulator: Accessibility Inspector → Settings

VoiceOver Testing Patterns

Simulating VoiceOver Experience

VoiceOver announces elements in accessibility tree order:

1. describe → Get accessibility tree
2. For each element (in order):
   - Announces: [label] [value] [traits] [hint]
   - Example: "Submit button, button, Sign in to your account"
3. Verify announcements are:
   ✓ Clear and descriptive
   ✓ Not redundant
   ✓ Appropriate detail level

Announcement structure:

"[label], [type], [value], [hint]"

Examples:
"Profile photo, image, image of John Doe"
"Volume, slider, 50%, adjustable"
"Send, button, button, Sends your message"

Common VoiceOver Issues

1. Verbose Announcements

Bad:  "Submit button, button, Click here to submit the form"
Good: "Submit, button"

Fix: Remove redundant "button" from label, concise hint.

2. Missing Context

Bad:  "Edit, button" (which item?)
Good: "Edit profile photo, button"

Fix: Include context in label.

3. Confusing Order

Visual:     [Title]  [Close button]
            [Content]
VoiceOver:  Close button → Content → Title  ❌

Fix: Adjust accessibility container order or element grouping.

4. No Label

Element visible, but:
- isAccessibilityElement: false (should be true)
- Or no accessibilityLabel

Fix: Set both properties appropriately.

Common Accessibility Violations

Issue: Image Without Label

Detection:

Query accessibility tree
Find elements with type: "Image"
Check if label is missing or generic

Symptoms:

  • VoiceOver says "image" or nothing
  • Screen reader users can't identify image

Fix:

imageView.isAccessibilityElement = true
imageView.accessibilityLabel = "Descriptive text"
// Or if decorative:
imageView.isAccessibilityElement = false

Issue: Buttons Without Labels

Detection:

Query accessibility tree
Find elements with traits: ["Button"]
Check if label is missing or just "button"

Symptoms:

  • VoiceOver says "button" with no context
  • Users don't know what button does

Fix:

button.accessibilityLabel = "Send message"
// Avoid: button.accessibilityLabel = "Send message button" // Redundant

Issue: Low Contrast Text

Detection:

Screenshot → Sample colors
Calculate contrast ratio
Compare to WCAG standards

Symptoms:

  • Hard to read in bright light
  • Fails WCAG AA (4.5:1)

Fix:

// Increase contrast
label.textColor = .label // System adapts to dark mode
// Or explicit colors with sufficient contrast
label.textColor = UIColor(white: 0.2, alpha: 1.0) // Dark gray on white

Issue: Complex Gestures Required

Detection:

Check if functionality requires:
- Multi-finger gestures
- Precise timing
- Specific swipe patterns

Symptoms:

  • Motor-impaired users can't activate
  • VoiceOver users can't navigate

Fix:

// Provide alternative single-tap interaction
// Or use standard UIControl components
// Avoid custom gesture-only interfaces

Issue: Non-Descriptive Link Text

Detection:

Query accessibility tree
Find elements with traits: ["Link"]
Check if label is generic: "click here", "read more"

Symptoms:

  • Screen reader users don't know destination
  • Can't scan links effectively

Fix:

// Bad
link.accessibilityLabel = "Click here"

// Good
link.accessibilityLabel = "Read our privacy policy"

Advanced Testing Patterns

Pattern: Form Validation

Test accessibility of error states:

1. describe → Get form elements
2. Submit invalid form
3. describe → Check error state
4. Verify:
   ✓ Error messages have labels
   ✓ Associated with relevant field
   ✓ Clear instructions for fixing
   ✓ Focus moves to first error

Good error accessibility:

{
  "type": "TextField",
  "label": "Email address",
  "value": "invalid",
  "traits": ["TextField"],
  "hint": "Invalid email format. Example: user@example.com"
}

Pattern: Dynamic Content

Test when content updates:

1. describe → Get initial state
2. Trigger update (load more, filter, etc.)
3. describe → Get new state
4. Verify:
   ✓ New content has labels
   ✓ Loading states announced
   ✓ Focus managed appropriately
   ✓ No duplicate announcements

Use accessibility notifications:

// Announce completion
UIAccessibility.post(notification: .announcement,
                     argument: "10 new messages loaded")

// Or move focus to new content
UIAccessibility.post(notification: .layoutChanged,
                     argument: firstNewElement)

Pattern: Modal/Dialog Testing

Test focus management:

1. describe → Get main screen elements
2. Open modal
3. describe → Get modal elements
4. Verify:
   ✓ Focus trapped in modal
   ✓ Background content not accessible
   ✓ Close button clearly labeled
   ✓ Modal has accessible title
5. Close modal
6. describe → Verify focus returns appropriately

Pattern: Pagination/Lists

Test large scrollable content:

For each page/section:
1. describe → Get visible elements
2. Verify logical reading order
3. Check:
   ✓ Item count announced ("Item 1 of 10")
   ✓ Headings mark sections
   ✓ Load more/pagination clear

Good pagination labels:

cell.accessibilityLabel = "Message from John, Item 5 of 42"
loadMoreButton.accessibilityLabel = "Load 20 more messages"

Automated Testing Integration

CI/CD Accessibility Checks

Basic audit in test pipeline:

1. Launch app to key screen
2. accessibility-quality-check → Get score
3. Assert score >= "good"
4. describe → Capture accessibility tree
5. Validate:
   - All buttons have labels
   - No images without labels (excluding decorative)
   - No duplicate labels in same context
   - Logical element order

Fail build if:

  • Score is "poor" or "insufficient"
  • Critical elements missing labels
  • New violations introduced (regression)

Regression Testing

Track accessibility over time:

1. Capture baseline accessibility tree (JSON)
2. On each commit:
   - Capture current tree
   - Compare to baseline
   - Flag new missing labels
   - Flag changed reading order
3. Review and approve changes or fix regressions

Troubleshooting

Problem: Element Not in Accessibility Tree

Symptoms:

  • Element visible but describe doesn't show it
  • VoiceOver skips element

Solutions:

  1. Check isAccessibilityElement = true
  2. Verify not hidden: isHidden = false
  3. Check not covered by another element
  4. Ensure frame is not CGRect.zero
  5. Verify accessibilityElementsHidden = false on parents

Problem: Wrong Reading Order

Symptoms:

  • Elements announced in illogical order
  • Navigation jumps around screen

Solutions:

  1. Check view hierarchy (Z-order affects reading order)
  2. Use accessibilityElements array to set explicit order:
    containerView.accessibilityElements = [label, field, button]
    
  3. Group related elements in accessibility containers

Problem: Insufficient Context

Symptoms:

  • Labels too generic: "button", "image", "item"
  • Users can't identify purpose

Solutions:

  1. Add specific context to label
  2. Include state information in value
  3. Use hint for non-obvious actions
  4. Consider combining multiple elements:
    containerView.isAccessibilityElement = true
    containerView.accessibilityLabel = "Email from John Doe, unread"
    

Best Practices

1. Accessibility-First Development

Design with accessibility from the start:

  • Use standard UIKit components (built-in support)
  • Plan semantic structure before visual design
  • Consider screen reader experience in wireframes
  • Test with VoiceOver during development

2. Semantic HTML/Structure

iOS equivalent:

  • Use appropriate UITraits (Button, Header, Link, etc.)
  • Group related content in accessibility containers
  • Use heading traits to mark sections
  • Adjust traits to match element behavior

3. Test with Real Users

Automated testing catches technical issues, but:

  • Real screen reader users find UX problems
  • Motor-impaired users reveal interaction issues
  • Test with VoiceOver on actual device
  • Observe usage patterns, not just compliance

4. Document Accessibility Decisions

// Intentionally not accessible - purely decorative
backgroundImage.isAccessibilityElement = false

// Combined for better experience - announces as single element
cardView.isAccessibilityElement = true
cardView.accessibilityLabel = "\(title), \(date), \(author)"
titleLabel.isAccessibilityElement = false
dateLabel.isAccessibilityElement = false
authorLabel.isAccessibilityElement = false

5. Maintain Accessibility Tree Quality

Set standards and enforce:

  • Minimum quality score: "good"
  • All interactive elements have labels
  • All images have labels or marked decorative
  • Contrast ratios meet AA standards
  • Forms have clear labels and error handling

Measure in CI/CD:

Run: accessibility-quality-check
Assert: score >= "good"
Run: describe → Parse accessibility tree
Assert: All buttons have labels
Assert: No generic labels ("button", "image")

Integration with MCP Tools

This Skill works with these MCP tools:

  • accessibility-quality-check: Quick assessment (~80ms)
  • idb-ui-describe: Full accessibility tree (~120ms)
  • idb-ui-find-element: Semantic element search (~100ms)
  • screenshot: Visual inspection (contrast, layout) (~2000ms)

Workflow integration:

1. accessibility-quality-check → Assess app quality
2. idb-ui-describe → Get detailed tree
3. Analyze semantic structure
4. screenshot → Verify contrast/visual (if needed)

Related Skills

  • ui-automation-workflows: Accessibility-first UI automation
  • ios-testing-patterns: Test strategy and CI integration
  • simulator-workflows: Device management for testing

Related Resources

  • xc://reference/accessibility: Accessibility API reference
  • xc://reference/wcag: WCAG 2.1 guidelines mapped to iOS
  • xc://workflows/accessibility-first: This workflow pattern
  • xc://examples/voiceover-testing: VoiceOver test examples

Remember: Accessibility tree is ground truth. Build accessible from the start. Test with real users.

Crash Debugging Skill

Comprehensive guide to iOS crash analysis and debugging

Quick Reference

TaskTool/CommandLocation
View crash logsConsole.appmacOS Application
Retrieve simulator crashes~/Library/Logs/DiagnosticReports/File system
Symbolicate crashatosCommand line
Find dSYM filesXcode Organizer / DerivedDataXcode
Analyze crash typeStack trace patternsCrash log

Overview

Crash debugging transforms cryptic crash logs into actionable insights. This skill covers:

  • Retrieving crash logs from simulators and devices
  • Understanding crash log structure
  • Symbolicating stack traces for readable function names
  • Identifying common crash patterns
  • Determining root causes

When to Use This Skill

Use this skill when:

  • App crashes during testing or development
  • Received crash reports from users or TestFlight
  • CI/CD pipeline reports test crashes
  • Need to symbolicate production crash logs
  • Investigating memory issues or crashes

Don't use for:

  • Build failures (see xcode-workflows)
  • Test assertion failures (see ios-testing-patterns)
  • UI debugging (see ui-automation-workflows)

Key Concepts

Crash Logs vs Diagnostic Reports

Crash Logs:

  • Generated when app terminates unexpectedly
  • Include exception type, stack trace, register state
  • Stored in DiagnosticReports directory
  • Named: AppName_YYYY-MM-DD-HHMMSS_DeviceName.crash

Diagnostic Reports:

  • Broader category including crashes, spins, hangs
  • May include system diagnostics
  • Same location as crash logs

Symbolication Process

Unsymbolicated:

0   MyApp    0x0000000102a3c4f8 0x102a38000 + 17656
1   MyApp    0x0000000102a3d1a4 0x102a38000 + 20900

Symbolicated:

0   MyApp    0x0000000102a3c4f8 ViewController.loginButtonTapped() + 120
1   MyApp    0x0000000102a3d1a4 ViewController.viewDidLoad() + 84

Symbolication Requirements:

  1. dSYM file matching the build UUID
  2. Binary (MyApp.app/MyApp)
  3. Crash log with memory addresses

Stack Traces and Debugging Symbols

Stack Trace:

  • List of function calls leading to crash
  • Ordered from crash point (top) to app entry (bottom)
  • Each line contains: frame number, binary name, address, symbol + offset

Debugging Symbols (dSYM):

  • Separate file containing symbol information
  • Maps memory addresses to function names
  • Generated during build (if "Debug Information Format" = "DWARF with dSYM")
  • Essential for crash analysis

Common Crash Types

Exception TypeMeaningCommon Cause
EXC_BAD_ACCESSInvalid memory accessDangling pointer, use-after-free
SIGABRTProcess abortedAssertion failure, force unwrap nil
EXC_BREAKPOINTBreakpoint hitSwift runtime error, fatal error
SIGILLIllegal instructionCorrupted code, wrong architecture
SIGSEGVSegmentation faultMemory corruption
SIGBUSBus errorUnaligned memory access

Workflows

Workflow 1: Crash Log Retrieval

From Simulator

Step 1: Locate Crash Logs

open ~/Library/Logs/DiagnosticReports/

Directory Structure:

DiagnosticReports/
├── MyApp_2025-11-06-143022_Conors-MacBook.crash
├── MyApp_2025-11-06-140511_Conors-MacBook.crash
└── ...

Step 2: Identify Recent Crash

Sort by date modified, or filter by app name:

ls -lt ~/Library/Logs/DiagnosticReports/ | grep MyApp | head -5

Step 3: Read Crash Log

cat ~/Library/Logs/DiagnosticReports/MyApp_2025-11-06-143022_Conors-MacBook.crash
From Console.app (Recommended)

Step 1: Open Console.app

open -a Console

Step 2: Filter Logs

  • Click "Crash Reports" in sidebar
  • Search for app name
  • Click crash report to view

Advantages:

  • Real-time monitoring
  • Better filtering and search
  • Automatic refresh
From Device (via Xcode)

Step 1: Connect Device

Step 2: Open Devices and Simulators

  • Xcode → Window → Devices and Simulators
  • Select device

Step 3: View Device Logs

  • Click "View Device Logs"
  • Find crash report
  • Right-click → Export

Workflow 2: Symbolication

Automatic Symbolication (Xcode)

Step 1: Locate dSYM

Xcode automatically symbolicates if:

  1. dSYM is in Spotlight index
  2. dSYM UUID matches crash log

Check dSYM UUID:

dwarfdump --uuid /path/to/MyApp.app.dSYM

Check Crash Log UUID:

Binary Images:
0x102a38000 - 0x102a4bfff MyApp arm64  <12345678-1234-1234-1234-123456789abc>

UUIDs must match for symbolication.

Step 2: Import to Xcode

If auto-symbolication fails:

  1. Xcode → Window → Organizer
  2. Select "Crashes" tab
  3. Drag crash log into window
  4. Xcode symbolicates automatically (if dSYM available)
Manual Symbolication (atos)

Step 1: Find Required Files

# App binary
APP_BINARY="/path/to/MyApp.app/MyApp"

# dSYM file
DSYM_FILE="/path/to/MyApp.app.dSYM/Contents/Resources/DWARF/MyApp"

# Load address (from crash log "Binary Images" section)
LOAD_ADDRESS="0x102a38000"

Step 2: Symbolicate Address

atos -arch arm64 -o "$DSYM_FILE" -l "$LOAD_ADDRESS" 0x0000000102a3c4f8

Output:

ViewController.loginButtonTapped() (in MyApp) (ViewController.swift:45)

Step 3: Symbolicate Multiple Addresses

atos -arch arm64 -o "$DSYM_FILE" -l "$LOAD_ADDRESS" \
  0x0000000102a3c4f8 \
  0x0000000102a3d1a4 \
  0x0000000102a3e220
Batch Symbolication (symbolicatecrash)

Symbolicate Entire Crash Log:

export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"

symbolicatecrash MyApp.crash MyApp.app.dSYM > MyApp_symbolicated.crash

Verify Symbolication:

grep -A 10 "Thread 0 Crashed" MyApp_symbolicated.crash

Should show function names, not just addresses.

Workflow 3: Stack Trace Analysis

Reading a Crash Log

Crash Log Structure:

Incident Identifier: 12345678-1234-1234-1234-123456789ABC
CrashReporter Key:   ABCDEF1234567890
Hardware Model:      iPhone15,2
Process:             MyApp [12345]
Path:                /private/var/containers/Bundle/Application/.../MyApp.app/MyApp
Identifier:          com.example.MyApp
Version:             1.0 (1)
Code Type:           ARM-64
Parent Process:      launchd [1]

Date/Time:           2025-11-06 14:30:22.123 +0000
OS Version:          iOS 17.0 (21A5326a)
Report Version:      104

Exception Type:      EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype:   KERN_INVALID_ADDRESS at 0x0000000000000000
Termination Reason:  SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [12345]

Triggered by Thread: 0

Thread 0 Crashed:
0   MyApp              0x0000000102a3c4f8 ViewController.loginButtonTapped() + 120
1   MyApp              0x0000000102a3d1a4 ViewController.viewDidLoad() + 84
2   UIKitCore          0x00000001b2e4c3a0 -[UIViewController loadViewIfRequired] + 928
...

Thread 1:
0   libsystem_kernel.dylib  0x00000001a2b3c4a8 __workq_kernreturn + 8
...

Binary Images:
0x102a38000 - 0x102a4bfff MyApp arm64  <12345678-1234-1234-1234-123456789abc>
...
Key Sections to Analyze

1. Exception Type

Exception Type:      EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype:   KERN_INVALID_ADDRESS at 0x0000000000000000
  • EXC_BAD_ACCESS: Memory access violation
  • KERN_INVALID_ADDRESS: Address doesn't exist (null pointer)
  • 0x0000000000000000: Accessing address zero (dereferencing nil)

2. Crashed Thread

Thread 0 Crashed:
0   MyApp              0x102a3c4f8 ViewController.loginButtonTapped() + 120
1   MyApp              0x102a3d1a4 ViewController.viewDidLoad() + 84
  • Frame 0 is crash location
  • Read from top to bottom (most recent to oldest)
  • Identify last app frame before system frames

3. Binary Images

0x102a38000 - 0x102a4bfff MyApp arm64  <12345678-1234-1234-1234-123456789abc>
  • Load address: 0x102a38000
  • UUID: 12345678-1234-1234-1234-123456789abc
  • Architecture: arm64

Workflow 4: Root Cause Identification

Step 1: Identify Crash Type

Match exception type to common patterns (see below).

Step 2: Locate Crash Point

Find the topmost frame in your app's code:

Thread 0 Crashed:
0   MyApp              0x102a3c4f8 ViewController.loginButtonTapped() + 120  ← START HERE
1   MyApp              0x102a3d1a4 ViewController.viewDidLoad() + 84
Step 3: Analyze Code Path
  1. Open file at crash location (ViewController.swift:45)
  2. Examine function loginButtonTapped()
  3. Check for:
    • Optional unwrapping (! or ?)
    • Array/dictionary access
    • Object references
    • Memory management
Step 4: Reproduce Locally
  1. Set breakpoint at crash location
  2. Follow stack trace path
  3. Inspect variables and state
  4. Identify null/invalid values
Step 5: Validate Fix
  1. Apply fix
  2. Build and test
  3. Verify no regression
  4. Monitor for related crashes

Common Crash Patterns

EXC_BAD_ACCESS (Memory Issues)

Signature:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000

Common Causes:

1. Dereferencing Nil (Swift)

// Crash:
let user: User? = nil
let name = user!.name  // EXC_BAD_ACCESS

// Fix:
if let name = user?.name {
    // Use name safely
}

2. Dangling Pointer (Objective-C)

// Crash:
@property (nonatomic, unsafe_unretained) id delegate;  // Dangerous
[self.delegate callMethod];  // Delegate deallocated → EXC_BAD_ACCESS

// Fix:
@property (nonatomic, weak) id<MyDelegate> delegate;

3. Use-After-Free

// Crash:
var buffer = UnsafeMutablePointer<Int>.allocate(capacity: 10)
buffer.deallocate()
buffer[0] = 42  // EXC_BAD_ACCESS

// Fix:
buffer[0] = 42
buffer.deallocate()

Debugging:

  • Enable Address Sanitizer (Scheme → Diagnostics → Address Sanitizer)
  • Check for weak vs unsafe_unretained references
  • Verify object lifecycle

SIGABRT (Assertion Failures)

Signature:

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: Namespace SIGNAL, Code 6 Abort trap: 6

Common Causes:

1. Force Unwrap Nil (Swift)

// Crash:
let value = dictionary["key"]!  // key doesn't exist → SIGABRT

// Stack trace shows:
Fatal error: Unexpectedly found nil while unwrapping an Optional value

// Fix:
if let value = dictionary["key"] {
    // Use value
}

2. Array Index Out of Bounds

// Crash:
let items = [1, 2, 3]
let item = items[10]  // Index out of range → SIGABRT

// Fix:
if items.indices.contains(10) {
    let item = items[10]
}

3. NSException (Objective-C)

// Crash:
[NSException raise:@"InvalidState" format:@"Unexpected condition"];

// Stack trace shows:
*** Terminating app due to uncaught exception 'InvalidState'

Debugging:

  • Read error message in crash log (very descriptive)
  • Check preconditions and assertions
  • Validate input data

EXC_BREAKPOINT (Swift Errors)

Signature:

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001a2b4c8d0

Common Causes:

1. Fatal Error

// Crash:
guard let user = currentUser else {
    fatalError("User must be logged in")  // EXC_BREAKPOINT
}

// Stack trace shows:
Fatal error: User must be logged in

// Fix:
guard let user = currentUser else {
    print("Error: User not logged in")
    return
}

2. Type Cast Failure (as!)

// Crash:
let value = anyValue as! String  // Value is not String → EXC_BREAKPOINT

// Fix:
if let value = anyValue as? String {
    // Use value
}

3. Precondition Failure

// Crash:
precondition(array.count > 0, "Array must not be empty")

// Fix:
if array.count > 0 {
    // Proceed safely
}

Debugging:

  • Read fatal error message in crash log
  • Review force casts (as!)
  • Check preconditions and guards

Timeout Crashes (Watchdog)

Signature:

Exception Type:  EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d

0x8badf00d = "ate bad food" = Watchdog timeout

Common Causes:

1. Main Thread Blocking

// Crash:
func viewDidLoad() {
    super.viewDidLoad()
    Thread.sleep(forTimeInterval: 30)  // Blocks main thread → Watchdog kills app
}

// Fix:
func viewDidLoad() {
    super.viewDidLoad()
    DispatchQueue.global().async {
        Thread.sleep(forTimeInterval: 30)
    }
}

2. Launch Time Timeout

App takes too long to launch (>20 seconds).

Fix:

  • Defer heavy initialization
  • Use background queues
  • Profile launch time

3. Suspend/Resume Timeout

App doesn't respond to backgrounding/foregrounding.

Fix:

  • Implement applicationDidEnterBackground quickly
  • Move long operations to background

Debugging:

  • Instrument Time Profiler
  • Check main thread operations
  • Review app lifecycle methods

Memory Issues (JETSAM)

Signature:

Exception Type:  EXC_RESOURCE
Exception Subtype: MEMORY
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: Namespace JETSAM, Code 0xdead10cc

Common Causes:

1. Memory Leak

// Leak:
class ViewController {
    var closure: (() -> Void)?

    func setup() {
        closure = {
            self.doSomething()  // Retain cycle
        }
    }
}

// Fix:
closure = { [weak self] in
    self?.doSomething()
}

2. Large Allocations

// Crash:
let hugeArray = Array(repeating: Data(count: 1_000_000), count: 1000)

// Fix:
// Process in chunks, release memory incrementally

Debugging:

  • Instruments → Allocations
  • Instruments → Leaks
  • Memory Graph Debugger (Xcode)

Troubleshooting

Missing Symbols

Problem: Stack trace shows addresses, not function names

Cause: Missing or mismatched dSYM file

Solutions:

  1. Find Correct dSYM
# List all dSYMs in DerivedData
find ~/Library/Developer/Xcode/DerivedData -name "*.dSYM" -type d

# Check UUID
dwarfdump --uuid /path/to/MyApp.app.dSYM
  1. Match UUID

Compare dSYM UUID with crash log Binary Images UUID. They must match exactly.

  1. Archive dSYMs

Enable "Archive" in scheme settings to preserve dSYMs for releases.

  1. Download from Xcode Organizer

For App Store builds:

  • Xcode → Window → Organizer
  • Select archive
  • Download dSYMs

Partial Stack Traces

Problem: Stack trace incomplete or truncated

Causes:

  • Tail call optimization
  • Inline functions
  • Missing debug symbols

Solutions:

  1. Disable Optimizations

Build Settings:

  • Optimization Level: None [-O0]
  • Debug Information Format: DWARF with dSYM File
  1. Build with Debug Configuration
{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Debug"
}
  1. Disable Inlining

Add -Xswiftc -Ounchecked to reduce optimizations.

System Framework Crashes

Problem: Crash in UIKit, Foundation, or other system framework

Stack Trace:

Thread 0 Crashed:
0   UIKitCore          0x00001b2e4c3a0 -[UIView layoutSubviews] + 928
1   UIKitCore          0x00001b2e5d1c4 -[UIView setNeedsLayout] + 84
2   MyApp              0x00102a3c4f8 ViewController.updateUI() + 45

Analysis:

  • Frame 2 is your code (start here)
  • System frameworks rarely crash on their own
  • Likely caused by invalid state or parameters from your code

Solutions:

  1. Check Parameters

Before system call, validate:

  • Non-nil objects
  • Valid ranges
  • Correct types
  1. Review Constraints

Auto Layout issues often cause UIKit crashes:

  • Check constraint conflicts
  • Verify view hierarchy
  1. Enable Exception Breakpoint

Xcode → Breakpoints → + → Exception Breakpoint

  • Catches issues before system framework crash

Third-Party Library Crashes

Problem: Crash in external library/framework

Stack Trace:

Thread 0 Crashed:
0   Alamofire          0x00001054a3c4f8 RequestAdapter.adapt() + 120
1   MyApp              0x00102a3c4f8 NetworkManager.fetchData() + 45

Solutions:

  1. Check Library Version

Ensure compatible version:

  • Update to latest stable
  • Check release notes for bug fixes
  1. Review Integration

Verify:

  • Correct API usage
  • Thread safety
  • Initialization order
  1. Enable Library Debug Symbols

In Podfile or SPM:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['DEBUG_INFORMATION_FORMAT'] = 'dwarf-with-dsym'
    end
  end
end
  1. Report Issue

If library bug:

  • Create minimal reproduction
  • File GitHub issue
  • Include crash log and steps

Tools & Commands

Console.app Usage

Launch:

open -a Console

Filter by App:

  1. Click "Crash Reports" in sidebar
  2. Enter app name in search
  3. Select crash to view

Export: Right-click crash → "Reveal in Finder" → Copy file

atos for Symbolication

Basic Usage:

atos -arch arm64 \
     -o /path/to/App.app.dSYM/Contents/Resources/DWARF/App \
     -l 0x100000000 \
     0x100001234

Parameters:

  • -arch: Architecture (arm64, x86_64)
  • -o: Path to dSYM or binary
  • -l: Load address from crash log
  • Last argument: Address to symbolicate

Multiple Addresses:

atos -arch arm64 -o MyApp.dSYM -l 0x100000000 \
  0x100001234 0x100002345 0x100003456

Xcode Organizer

Access: Xcode → Window → Organizer

Features:

  • View archives
  • Download dSYMs for App Store builds
  • View crash reports from TestFlight/App Store
  • Automatic symbolication

Crashes Tab:

  • Aggregate crashes from users
  • Group by crash signature
  • Filter by OS version, device

lldb Debugging

Set Breakpoint:

(lldb) breakpoint set --name ViewController.loginButtonTapped
(lldb) breakpoint set --file ViewController.swift --line 45

Examine Variables:

(lldb) po user
(lldb) p user?.name
(lldb) frame variable

Navigate Stack:

(lldb) bt                 # Print backtrace
(lldb) frame select 2     # Switch to frame 2
(lldb) up                 # Move up stack
(lldb) down               # Move down stack

Memory Inspection:

(lldb) memory read 0x100001234
(lldb) register read

Integration with Simulator Workflows

Reproduce Crash in Simulator

Workflow:

1. Build app (xcode-workflows)
2. Boot simulator (simulator-workflows → boot)
3. Install app (simulator-workflows → install)
4. Launch with lldb attached (Xcode → Debug)
5. Reproduce crash
6. Analyze in debugger

Retrieve Logs:

1. Crash occurs in simulator
2. Console.app → Filter by app name
3. Or: ls ~/Library/Logs/DiagnosticReports/ | grep MyApp
4. Read crash log
5. Symbolicate if needed

Related Skills

  • simulator-workflows: App lifecycle and device management
  • xcode-workflows: Building with debug symbols
  • ios-testing-patterns: Preventing crashes through testing

Related Resources

  • xc://reference/crash-types: Complete crash type reference
  • xc://workflows/symbolication: Detailed symbolication guide
  • xc://tools/debugging: LLDB and debugging tools reference

Tip: Enable Address Sanitizer and Undefined Behavior Sanitizer in scheme diagnostics to catch memory issues early.

iOS Testing Patterns Skill

Comprehensive guide to XCTest and XCUITest execution, analysis, and flaky test detection

Overview

This skill provides patterns and workflows for executing iOS tests using XCTest and XCUITest frameworks. It covers test execution strategies, result analysis, flaky test detection, and troubleshooting common test failures.

Use this skill when:

  • Running unit tests or UI tests
  • Analyzing test failures
  • Detecting and debugging flaky tests
  • Optimizing test execution performance
  • Setting up CI/CD test pipelines

Quick Reference

TaskOperationKey Parameters
Run all teststestscheme, destination
Run specific testtestscheme, only_testing
Skip teststestscheme, skip_testing
Use test plantestscheme, test_plan
Parallel executiontestdestination (multiple)

When to Use This Skill

Use ios-testing-patterns when:

  • Executing XCTest unit tests
  • Running XCUITest UI automation tests
  • Investigating test failures
  • Detecting intermittent test failures (flaky tests)
  • Analyzing test performance and execution time
  • Setting up test schemes and test plans
  • Configuring parallel test execution
  • Debugging test-specific simulator issues

Related Skills:

  • xcode-workflows: For general build and test operations
  • simulator-workflows: For managing test simulators
  • ui-automation-workflows: For UI test interaction patterns

Key Concepts

XCTest vs XCUITest

XCTest (Unit/Integration Tests):

  • Fast execution (milliseconds to seconds)
  • Tests individual components in isolation
  • Direct access to app internals
  • No UI interaction required
  • Runs in same process as app code

XCUITest (UI Tests):

  • Slower execution (seconds to minutes)
  • Tests user-facing workflows
  • Black-box testing (no app internals)
  • Requires simulator/device UI
  • Runs in separate process

Test Execution Strategies

Sequential Execution:

  • Tests run one after another
  • Predictable, repeatable results
  • Slower overall execution
  • Better for debugging

Parallel Execution:

  • Tests run simultaneously on multiple simulators
  • Faster overall execution
  • Requires more system resources
  • May expose race conditions

Test Sharding:

  • Split test suite across multiple destinations
  • Optimal for CI/CD pipelines
  • Reduces total execution time
  • Requires careful test isolation

Workflows

1. Running Unit Tests

Basic Unit Test Execution:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15,OS=18.0"
}

Note: The destination parameter now supports auto-resolution! You can omit the OS version (e.g., "platform=iOS Simulator,name=iPhone 15") and the tool will automatically select the latest available OS version for that device.

Run Specific Test Class:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15,OS=18.0",
  "options": {
    "only_testing": ["MyAppTests/NetworkTests"]
  }
}

Run Specific Test Method:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15,OS=18.0",
  "options": {
    "only_testing": ["MyAppTests/NetworkTests/testAPIRequest"]
  }
}

2. Running UI Tests

Basic UI Test Execution:

{
  "operation": "test",
  "scheme": "MyAppUITests",
  "destination": "platform=iOS Simulator,name=iPhone 15"
}

UI Tests with Specific Device:

{
  "operation": "test",
  "scheme": "MyAppUITests",
  "destination": "platform=iOS Simulator,name=iPad Pro (12.9-inch)"
}

UI Tests with Test Plan:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "test_plan": "SmokeTests"
  }
}

3. Parallel Test Execution

Multiple Destinations:

Run tests on multiple simulators simultaneously:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": [
    "platform=iOS Simulator,name=iPhone 15",
    "platform=iOS Simulator,name=iPhone SE (3rd generation)"
  ],
  "options": {
    "parallel": true
  }
}

Parallel Test Benefits:

  • Reduces total execution time
  • Tests across multiple device types
  • Exposes device-specific issues
  • Better CI/CD performance

Parallel Test Considerations:

  • Requires multiple simulators
  • Higher CPU/memory usage
  • May expose race conditions
  • Test isolation critical

4. Test Filtering

Skip Specific Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "skip_testing": [
      "MyAppUITests/SlowTests",
      "MyAppTests/NetworkTests/testLargeDownload"
    ]
  }
}

Run Only Fast Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "only_testing": ["MyAppTests/UnitTests"],
    "skip_testing": ["MyAppTests/UnitTests/testSlowOperation"]
  }
}

5. Test Result Analysis

Success Response:

{
  "success": true,
  "tests_run": 45,
  "tests_passed": 45,
  "tests_failed": 0,
  "execution_time": "12.4s",
  "scheme": "MyApp"
}

Failure Response:

{
  "success": false,
  "tests_run": 45,
  "tests_passed": 43,
  "tests_failed": 2,
  "failures": [
    {
      "test": "MyAppTests.LoginTests.testInvalidPassword",
      "message": "XCTAssertEqual failed: (\"error\") is not equal to (\"invalid\")",
      "file": "LoginTests.swift",
      "line": 42
    },
    {
      "test": "MyAppUITests.CheckoutTests.testPaymentFlow",
      "message": "Failed to find button \"Confirm\"",
      "file": "CheckoutTests.swift",
      "line": 78
    }
  ],
  "execution_time": "18.7s"
}

Analyzing Test Results:

  1. Check success status
  2. Review tests_failed count
  3. Examine failures array for details
  4. Check execution_time for performance issues
  5. Look for patterns in failure messages

6. Flaky Test Detection

What are Flaky Tests?

Tests that intermittently pass or fail without code changes:

  • Timing-dependent assertions
  • Race conditions
  • Async operation issues
  • Shared state between tests
  • Network-dependent tests
  • UI animation timing issues

Detection Strategy 1: Multiple Runs

Run tests multiple times to detect flakiness:

# Run tests 5 times and compare results
for i in {1..5}; do
  execute_xcode_command(test, scheme, destination)
  # Record results
done

Detection Strategy 2: Pattern Analysis

Look for common flaky test patterns:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "only_testing": ["MyAppTests/SuspectedFlakyTest"]
  }
}

Flaky Test Indicators:

  1. Timeout failures: "Exceeded timeout of 30 seconds"
  2. Element not found: "Failed to find button..." (UI tests)
  3. Race conditions: "Expected 5 but got 4"
  4. Async timing: "Asynchronous wait failed"
  5. Network failures: "Request timed out"

Flaky Test Workflow:

1. Identify suspect test (intermittent failures)
2. Run test 10+ times in isolation
3. Analyze failure patterns
4. Check for:
   - Hard-coded waits (sleep/wait)
   - Expectation timeouts too short
   - Shared mutable state
   - Network dependencies
   - Animation timing assumptions
5. Fix root cause
6. Verify with repeated runs

7. Test Isolation

Clean State Before Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "clean_before_build": true
  }
}

Reset Simulator State:

# Use simulator-workflows skill
execute_simulator_command(operation: "erase", udid: <device-udid>)

Test Isolation Best Practices:

  1. Use setUp() and tearDown() methods
  2. Clear app state between tests
  3. Use unique test data per test
  4. Avoid shared static state
  5. Reset UserDefaults in setUp
  6. Clear keychain data
  7. Reset app permissions

Common Patterns

Test Scheme Configuration

Typical Test Scheme Setup:

  • Build Configuration: Debug (faster builds)
  • Test Plans: Separate unit/UI/smoke tests
  • Coverage: Enable code coverage collection
  • Diagnostics: Enable thread sanitizer for threading issues

Multiple Test Plans:

UnitTests.xctestplan       → Fast unit tests only
UITests.xctestplan         → UI automation tests
SmokeTests.xctestplan      → Critical path tests
RegressionTests.xctestplan → Full test suite

Test Data Management

Pattern 1: Test Fixtures

class TestData {
    static let validUser = User(name: "Test", email: "test@example.com")
    static let invalidUser = User(name: "", email: "invalid")
}

Pattern 2: Factory Methods

extension User {
    static func makeTestUser(name: String = "Test") -> User {
        return User(name: name, email: "\(name)@test.com")
    }
}

Pattern 3: Test Database

class TestDatabase {
    func setupTestData() {
        // Create known test data
    }

    func teardownTestData() {
        // Clean up after tests
    }
}

Screenshot Capture on Failure

UI Test Screenshot Pattern:

override func setUp() {
    continueAfterFailure = false
}

override func tearDown() {
    if let testRun = testRun, testRun.failureCount > 0 {
        let screenshot = XCUIScreen.main.screenshot()
        let attachment = XCTAttachment(screenshot: screenshot)
        attachment.lifetime = .keepAlways
        add(attachment)
    }
}

Execute Tests with Screenshots:

{
  "operation": "test",
  "scheme": "MyAppUITests",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "result_bundle_path": "./TestResults.xcresult"
  }
}

Performance Testing

XCTest Performance Measurement:

func testPerformance() {
    measure {
        // Code to measure
        performExpensiveOperation()
    }
}

Performance Test Execution:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "only_testing": ["MyAppTests/PerformanceTests"]
  }
}

Troubleshooting

Common Test Failures

1. "Test crashed with signal SIGABRT"

Causes:

  • Force unwrapping nil values
  • Array index out of bounds
  • Precondition/assertion failures
  • Fatal errors in app code

Solutions:

  1. Check crash logs for stack trace
  2. Run test in debugger (Xcode)
  3. Add breakpoints at crash location
  4. Review force unwraps in test path
2. "Failed to find element/button"

Causes:

  • Element not yet rendered
  • Animation not complete
  • Incorrect accessibility identifier
  • Element off-screen

Solutions:

  1. Increase timeout for element queries
  2. Wait for animations to complete
  3. Verify accessibility identifiers
  4. Scroll element into view
  5. Check element existence before interaction

Example Fix:

// Bad: Immediate query may fail
app.buttons["Submit"].tap()

// Good: Wait for element
let submitButton = app.buttons["Submit"]
XCTAssert(submitButton.waitForExistence(timeout: 5))
submitButton.tap()
3. "Exceeded timeout of X seconds"

Causes:

  • Network requests too slow
  • Async operations not completing
  • Deadlocks or infinite loops
  • Expectations never fulfilled

Solutions:

  1. Increase expectation timeout
  2. Mock network requests
  3. Check for deadlocks
  4. Verify expectation fulfillment
  5. Use proper async testing patterns

Example Fix:

// Bad: May timeout
wait(for: [expectation], timeout: 1.0)

// Good: Reasonable timeout
wait(for: [expectation], timeout: 10.0)
4. "Test failed due to app termination"

Causes:

  • Memory pressure
  • Watchdog timeout (app hung)
  • Background task limits
  • System resource constraints

Solutions:

  1. Profile memory usage
  2. Optimize test efficiency
  3. Break up long-running tests
  4. Check for memory leaks
  5. Reduce simulator load

Timeout Issues

UI Test Timeouts:

{
  "operation": "test",
  "scheme": "MyAppUITests",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "test_timeout": 600
  }
}

Common Timeout Scenarios:

  1. App Launch Timeout: App takes too long to launch

    • Solution: Optimize app startup, increase timeout
  2. Element Query Timeout: UI element not found

    • Solution: Wait for element existence, check identifiers
  3. Network Timeout: API requests fail

    • Solution: Mock network, increase timeout, fix connectivity
  4. Animation Timeout: Waiting for animation

    • Solution: Disable animations in tests, use proper waits

Simulator State Problems

Symptom: Tests fail due to simulator state

Common Issues:

  1. Previous app installation interfering
  2. Simulator storage full
  3. Corrupt simulator data
  4. Multiple tests modifying shared state

Solutions:

# Erase simulator before tests
execute_simulator_command({
  "operation": "erase",
  "udid": "<simulator-udid>"
})

# Then run tests
execute_xcode_command({
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15"
})

Test Dependency Issues

Symptom: Tests pass individually but fail in suite

Causes:

  • Test execution order dependencies
  • Shared mutable state
  • Singleton pollution
  • Database state carryover

Solutions:

  1. Ensure Test Isolation:
override func setUp() {
    super.setUp()
    // Reset all shared state
    AppState.shared.reset()
    clearDatabase()
}
  1. Avoid Singletons:
// Bad: Shared state
class APIManager {
    static let shared = APIManager()
}

// Good: Dependency injection
class APIManager {
    // Inject per test
}
  1. Randomize Test Order:
{
  "operation": "test",
  "scheme": "MyApp",
  "options": {
    "test_order": "random"
  }
}

Best Practices

1. Test Isolation

Always isolate tests:

  • Each test should run independently
  • No shared state between tests
  • Clean up in tearDown()
  • Use unique test data

Example:

class UserTests: XCTestCase {
    var sut: UserManager!

    override func setUp() {
        super.setUp()
        sut = UserManager()
    }

    override func tearDown() {
        sut = nil
        super.tearDown()
    }

    func testCreateUser() {
        // Test uses fresh sut instance
    }
}

2. Fast Test Execution

Optimize test speed:

  • Mock network requests
  • Use in-memory databases
  • Disable animations in UI tests
  • Avoid actual file I/O
  • Use test doubles (mocks/stubs)

UI Test Speed:

// Disable animations for faster tests
app.launchArguments += ["DISABLE_ANIMATIONS"]

3. Readable Test Names

Use descriptive test names:

// Bad
func test1() { }

// Good
func testLoginWithValidCredentialsSucceeds() { }
func testLoginWithInvalidPasswordShowsError() { }
func testCheckoutWithEmptyCartDisplaysWarning() { }

4. Arrange-Act-Assert Pattern

Structure tests clearly:

func testAddItemToCart() {
    // Arrange
    let cart = ShoppingCart()
    let item = Product(name: "Test", price: 10)

    // Act
    cart.add(item)

    // Assert
    XCTAssertEqual(cart.items.count, 1)
    XCTAssertEqual(cart.total, 10)
}

5. Test Data Management

Use consistent test data:

struct TestFixtures {
    static let validEmail = "test@example.com"
    static let invalidEmail = "invalid"
    static let testUser = User(name: "Test", email: validEmail)
}

6. CI/CD Integration

CI Test Workflow:

1. Clean build environment
2. Build app for testing
3. Boot fresh simulator
4. Run test suite
5. Collect code coverage
6. Parse test results
7. Archive test artifacts
8. Report results

CI Test Command:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "clean_before_build": true,
    "code_coverage": true,
    "result_bundle_path": "./TestResults.xcresult"
  }
}

7. Test Pyramid

Maintain proper test distribution:

      /\
     /UI\      ← Few, slow, broad
    /----\
   /Integ\     ← Some, medium, focused
  /------\
 /  Unit  \    ← Many, fast, isolated
/----------\

Recommended ratio:

  • 70% Unit tests
  • 20% Integration tests
  • 10% UI tests

8. Code Coverage

Enable coverage collection:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "code_coverage": true
  }
}

Coverage goals:

  • Critical paths: 90%+ coverage
  • Business logic: 80%+ coverage
  • UI code: 60%+ coverage
  • Overall: 75%+ coverage

9. Continuous Test Monitoring

Track test metrics:

  • Test execution time trends
  • Flaky test frequency
  • Test failure rate
  • Code coverage trends
  • Test suite growth

When to investigate:

  • Test execution time increases >20%
  • Flaky tests appear
  • Coverage drops
  • Failure rate increases

Related Skills

  • xcode-workflows: General build and test operations
  • simulator-workflows: Managing test simulators and devices
  • ui-automation-workflows: Advanced UI test interaction patterns
  • crash-debugging: Analyzing test crashes

Related Resources

  • xc://operations/test: Complete test operations reference
  • xc://reference/xctest: XCTest framework documentation
  • xc://reference/xcuitest: XCUITest framework documentation
  • xc://patterns/flaky-tests: Flaky test detection patterns

Tip: Isolate tests, mock dependencies, and run tests frequently during development.

Performance Profiling Skill

Comprehensive guide to iOS performance analysis and optimization

Overview

Performance profiling is the systematic analysis of an iOS app's runtime behavior to identify bottlenecks, memory issues, network inefficiencies, and energy consumption patterns. This Skill guides you through using Instruments templates, interpreting profiling data, and applying optimization strategies.

Key Tools:

  • Instruments (Xcode's profiling suite)
  • xcodebuild for profiling builds
  • Performance metrics analysis
  • Memory graph debugging

When to Use This Skill

Use performance profiling when:

  1. App Performance Issues

    • Slow app launch times
    • Choppy scrolling or animations
    • UI freezing or unresponsiveness
    • High CPU usage
  2. Memory Problems

    • Memory leaks detected
    • Growing memory footprint
    • Memory warnings
    • App crashes due to memory pressure
  3. Network Inefficiencies

    • Slow data loading
    • Excessive network requests
    • Large payload sizes
    • Poor offline handling
  4. Energy Consumption

    • Battery drain complaints
    • Background processing issues
    • Thermal throttling
    • Energy impact reports
  5. Pre-Release Optimization

    • Performance regression detection
    • Baseline performance establishment
    • Release candidate validation
    • Performance budget enforcement

Key Concepts

Instruments Templates

Time Profiler

  • Measures CPU usage and call stacks
  • Identifies hot paths in code
  • Shows function-level performance
  • Best for: CPU-bound operations, algorithm optimization

Allocations

  • Tracks memory allocations and deallocations
  • Shows object lifetime and retention
  • Identifies memory growth patterns
  • Best for: Memory footprint analysis, allocation hotspots

Leaks

  • Detects memory leaks in real-time
  • Shows leaked objects and their origins
  • Identifies retain cycles
  • Best for: Finding memory leaks, debugging reference cycles

Network

  • Monitors HTTP/HTTPS traffic
  • Shows request/response timing
  • Tracks payload sizes
  • Best for: API optimization, bandwidth analysis

Energy Log

  • Measures energy consumption
  • Shows CPU, network, display impact
  • Identifies battery drain sources
  • Best for: Battery life optimization

Core Animation

  • Analyzes frame rate and rendering
  • Shows layer composition issues
  • Identifies off-screen rendering
  • Best for: Animation optimization, scrolling performance

Profiling Strategies

Sampling vs Tracing

Sampling (Time Profiler):

  • Periodically captures call stacks
  • Low overhead (~5-10%)
  • May miss short-lived operations
  • Best for: Production-like scenarios

Tracing (Most other instruments):

  • Records every event
  • Higher overhead (10-50%)
  • Complete event history
  • Best for: Detailed analysis

Performance Metrics

Launch Time

  • Pre-main time: Dynamic library loading, +load methods
  • Main to first frame: App initialization, first view load
  • Target: < 400ms total on device

Scrolling Performance

  • Frame rate: 60 FPS (16.67ms per frame)
  • Hitch ratio: < 5ms hitches per second
  • Target: 60 FPS sustained during scrolling

Memory Footprint

  • Resident memory: Actual physical RAM used
  • Dirty memory: Memory written to by app
  • Target: Depends on device (< 150MB for low-end devices)

Network Efficiency

  • Request latency: Time to first byte
  • Transfer size: Payload + overhead
  • Request frequency: Requests per minute
  • Target: < 100KB per request, batch when possible

Energy Impact

  • CPU time: Processor usage
  • Network bytes: Data transferred
  • Display time: Screen on time
  • Target: "Low" or "Medium" energy impact rating

Workflows

CPU Profiling (Time Profiler)

Goal: Identify CPU-intensive operations and optimize hot paths

Step 1: Build for Profiling

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Release",
  "destination": "platform=iOS,id=<device-udid>",
  "options": {
    "archive_for_profiling": true
  }
}

Why Release Configuration?

  • Enables optimizations
  • Reflects production performance
  • Removes debug overhead

Device vs Simulator:

  • Always profile on device for accurate CPU measurements
  • Simulator runs on Mac CPU (not representative)

Step 2: Profile with Instruments

# Launch Instruments with Time Profiler template
instruments -t "Time Profiler" \
  -D /path/to/trace.trace \
  -w <device-udid> \
  com.example.MyApp

Manual Approach:

  1. Open Instruments (Xcode → Open Developer Tool → Instruments)
  2. Select "Time Profiler" template
  3. Choose device and app
  4. Click record, perform problematic operations
  5. Stop recording

Step 3: Analyze Call Tree

Call Tree Settings:

  • Enable "Separate by Thread"
  • Enable "Hide System Libraries" (initially)
  • Show "Heaviest Stack Trace"

Interpret Results:

  • Self Time: Time spent in function itself
  • Total Time: Time including called functions
  • Call Count: Number of times function called

Red Flags:

  • Self time > 50ms for UI operations
  • High call count for expensive operations
  • Unexpected functions in hot path

Step 4: Optimize

Common Optimizations:

  • Reduce algorithm complexity (O(n²) → O(n log n))
  • Cache expensive computations
  • Move work off main thread
  • Use lazy evaluation

Verification:

  • Profile again after changes
  • Compare before/after traces
  • Ensure optimization didn't break functionality

Memory Profiling (Allocations & Leaks)

Goal: Identify memory leaks and reduce memory footprint

Step 1: Build for Profiling

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Debug",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "enable_memory_debugging": true
  }
}

Note: Use Debug for better stack traces, Simulator acceptable for memory profiling

Step 2: Profile with Allocations

# Launch Instruments with Allocations template
instruments -t "Allocations" \
  -D /path/to/allocations.trace \
  -w <simulator-udid> \
  com.example.MyApp

Step 3: Identify Memory Growth

Heap Growth Analysis:

  1. Take memory snapshot (Mark Generation)
  2. Perform operation (e.g., open/close view controller)
  3. Take another snapshot
  4. View "Growth" column

Expected: Minimal growth after repeated operations Red Flag: Continuous growth with each iteration

Step 4: Find Leaks

Switch to Leaks Instrument:

instruments -t "Leaks" \
  -D /path/to/leaks.trace \
  -w <simulator-udid> \
  com.example.MyApp

Interpret Results:

  • Leaks shown in red
  • Click leak → See responsible stack trace
  • Common causes: Retain cycles, unregistered observers

Step 5: Debug Retain Cycles

Memory Graph Debugger:

  1. Run app in Xcode
  2. Click "Debug Memory Graph" button
  3. Filter by leaked objects
  4. Inspect retain cycle paths

Common Patterns:

  • Closure capturing self strongly
  • Delegate not marked weak
  • NSNotificationCenter observers not removed
  • Timer retaining target

Solutions:

  • Use [weak self] in closures
  • Mark delegates as weak
  • Remove observers in deinit
  • Invalidate timers properly

Network Profiling

Goal: Optimize network requests and reduce data usage

Step 1: Profile with Network Instrument

instruments -t "Network" \
  -D /path/to/network.trace \
  -w <device-udid> \
  com.example.MyApp

Step 2: Analyze Network Activity

Key Metrics:

  • Request Count: Total number of requests
  • Bytes Transferred: Upload + download size
  • Duration: Time from request to completion
  • HTTP Status: Success/failure codes

Red Flags:

  • Many small requests (should batch)
  • Large payloads (should paginate)
  • Sequential requests (should parallelize)
  • Redundant requests (should cache)

Step 3: Optimize Requests

Batching:

// Before: 10 separate requests
for item in items {
    fetchDetails(for: item)
}

// After: 1 batched request
fetchDetails(for: items)

Pagination:

// Fetch 20 items at a time
func fetchItems(page: Int, pageSize: Int = 20) {
    let offset = page * pageSize
    api.fetch(limit: pageSize, offset: offset)
}

Caching:

// Use URLCache or custom cache
let cache = URLCache.shared
cache.diskCapacity = 50 * 1024 * 1024 // 50MB

Compression:

// Enable gzip compression
request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")

Energy Profiling

Goal: Reduce battery drain and thermal impact

Step 1: Profile with Energy Log

instruments -t "Energy Log" \
  -D /path/to/energy.trace \
  -w <device-udid> \
  com.example.MyApp

Step 2: Analyze Energy Impact

Energy Sources:

  • CPU: Processing time
  • Network: Data transfer
  • Display: Screen updates
  • Location: GPS usage
  • Background: Background processing

Energy Levels:

  • Low: 0-10 energy units
  • Medium: 10-40 energy units
  • High: > 40 energy units

Target: Stay in "Low" or "Medium" most of the time

Step 3: Optimize Energy Usage

CPU Optimization:

  • Reduce background processing
  • Use efficient algorithms
  • Defer non-critical work

Network Optimization:

  • Batch requests
  • Use compression
  • Schedule background transfers

Display Optimization:

  • Reduce animation complexity
  • Dim screen when possible
  • Pause animations when offscreen

Location Optimization:

  • Use lowest accuracy needed
  • Stop updates when not needed
  • Use significant location changes

Common Profiling Patterns

Launch Time Optimization

Measurement Approach:

  1. Profile App Launch
instruments -t "App Launch" \
  -D /path/to/launch.trace \
  -w <device-udid> \
  com.example.MyApp
  1. Analyze Pre-Main Time
    • Dynamic library loading
    • Objective-C class registration
    • +load method execution

Optimization Strategies:

  • Reduce number of dynamic libraries
  • Move +load work to +initialize
  • Lazy load unnecessary frameworks
  1. Analyze Main to First Frame
    • UIApplicationMain execution
    • didFinishLaunching execution
    • First view controller load

Optimization Strategies:

  • Defer heavy initialization
  • Load critical UI first
  • Use placeholders for slow content

Target: < 400ms total launch time on device

Scroll Performance Analysis

Measurement Approach:

  1. Profile Scrolling
instruments -t "Core Animation" \
  -D /path/to/scroll.trace \
  -w <device-udid> \
  com.example.MyApp
  1. Check Frame Rate

    • Target: 60 FPS (16.67ms per frame)
    • Acceptable: 50-60 FPS
    • Poor: < 50 FPS
  2. Identify Frame Drops

    • Look for red/yellow bars in timeline
    • Check "Time Profiler" for main thread work

Optimization Strategies:

Cell Reuse:

// Proper cell reuse
func tableView(_ tableView: UITableView,
               cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    configure(cell: cell, with: data[indexPath.row])
    return cell
}

Image Optimization:

// Downsize images to display size
let size = imageView.bounds.size
let downsizedImage = image.resized(to: size)
imageView.image = downsizedImage

Layout Caching:

// Cache calculated heights
private var heightCache: [IndexPath: CGFloat] = [:]

func tableView(_ tableView: UITableView,
               heightForRowAt indexPath: IndexPath) -> CGFloat {
    if let height = heightCache[indexPath] {
        return height
    }
    let height = calculateHeight(for: indexPath)
    heightCache[indexPath] = height
    return height
}

Off-Main-Thread Work:

// Move image processing off main thread
DispatchQueue.global(qos: .userInitiated).async {
    let processedImage = self.processImage(image)
    DispatchQueue.main.async {
        self.imageView.image = processedImage
    }
}

Memory Leak Detection

Systematic Approach:

  1. Identify Suspect Feature

    • Feature that shows memory growth
    • Example: Opening/closing profile view
  2. Create Reproduction Steps

    1. Launch app
    2. Open profile view
    3. Close profile view
    4. Repeat 10 times
    
  3. Profile with Leaks

    • Use Leaks instrument
    • Follow reproduction steps
    • Check for leaks after each iteration
  4. Analyze Leak Origin

    • Click leaked object
    • View "Responsible Caller"
    • Trace back to source code
  5. Identify Leak Pattern

    • Closure capture: [weak self] missing
    • Delegate: Not marked weak
    • Notification: Observer not removed
    • Timer: Not invalidated
  6. Fix and Verify

    • Apply fix
    • Profile again
    • Confirm leak eliminated

Network Request Optimization

Analysis Workflow:

  1. Baseline Measurement

    • Profile typical user session
    • Count total requests
    • Measure total bytes transferred
  2. Identify Inefficiencies

    • Too many requests: Batch or consolidate
    • Large payloads: Compress or paginate
    • Redundant data: Implement caching
    • Sequential requests: Parallelize when possible
  3. Optimization Strategies

Request Batching:

// Batch multiple IDs into single request
func fetchUsers(ids: [String]) {
    let batchedIDs = ids.joined(separator: ",")
    api.get("/users?ids=\(batchedIDs)")
}

Response Pagination:

// Implement cursor-based pagination
func fetchFeed(cursor: String? = nil, limit: Int = 20) {
    var params = ["limit": limit]
    if let cursor = cursor {
        params["cursor"] = cursor
    }
    api.get("/feed", parameters: params)
}

Intelligent Caching:

// Cache with expiration
class APICache {
    private var cache: [String: CachedResponse] = [:]

    func get(url: String) -> Data? {
        guard let cached = cache[url],
              !cached.isExpired else { return nil }
        return cached.data
    }

    func set(url: String, data: Data, ttl: TimeInterval = 300) {
        cache[url] = CachedResponse(data: data, expiry: Date() + ttl)
    }
}

Request Coalescing:

// Prevent duplicate in-flight requests
class RequestCoalescer {
    private var inFlightRequests: [String: Task<Data, Error>] = [:]

    func request(url: String) async throws -> Data {
        if let existing = inFlightRequests[url] {
            return try await existing.value
        }

        let task = Task {
            let data = try await performRequest(url)
            inFlightRequests[url] = nil
            return data
        }

        inFlightRequests[url] = task
        return try await task.value
    }
}

Analysis Techniques

Call Tree Interpretation

Understanding Call Tree Structure:

Total Time | Self Time | Symbol
-----------|-----------|--------
  1000ms   |   10ms    | -[UITableView reloadData]
   800ms   |   50ms    |  └─ -[MyCell configure]
   700ms   |  700ms    |     └─ -[ImageProcessor processImage]

Reading:

  • reloadData took 1000ms total
  • 10ms in reloadData itself
  • 800ms in configure (called from reloadData)
  • 700ms in processImage (called from configure)

Optimization Target: processImage (700ms self time)

Call Tree Filters:

Separate by Thread:

  • Shows which threads are busy
  • Identify main thread bottlenecks

Hide System Libraries:

  • Focus on your code
  • Re-enable to see system call overhead

Flatten Recursion:

  • Collapses recursive calls
  • Shows total time in recursive function

Show Obj-C Only / Swift Only:

  • Filter by language
  • Useful in mixed codebases

Flame Graph Reading

Visual Representation:

  • Width = Time spent
  • Height = Call stack depth
  • Color = Different functions

Interpretation:

  • Wide sections = Hot spots (spend optimization time here)
  • Tall stacks = Deep call chains (consider flattening)
  • Repeated patterns = Loop opportunities

Example:

[                    main                    ] ← 100% of time
[       viewDidLoad       ][    updateUI    ] ← 50% each
[loadData][parseJSON]      [layout][render] ← Breakdown

Optimization Strategy:

  • Focus on widest sections first
  • Consider parallelizing separate wide sections
  • Optimize functions appearing multiple times

Memory Graph Debugging

Workflow:

  1. Capture Memory Graph

    • Run app in Xcode
    • Click "Debug Memory Graph" button (or ⌘⌥M)
  2. Filter View

    • Filter by "Leaks" to see leaked objects
    • Filter by class name to find specific objects
  3. Inspect Object

    • Select object in left panel
    • View properties in right panel
    • See references in reference inspector
  4. Trace Retain Cycle

    • Follow strong references
    • Identify circular paths
    • Note where weak should be used

Example Cycle:

ViewController → (strong) Closure → (strong) ViewController

Fix:

// Before (leak)
viewModel.onUpdate = {
    self.updateUI()
}

// After (no leak)
viewModel.onUpdate = { [weak self] in
    self?.updateUI()
}

Performance Regression Detection

Continuous Performance Testing:

  1. Establish Baseline

    • Profile app on reference device
    • Record key metrics (launch time, memory, FPS)
    • Store baseline measurements
  2. Automated Performance Tests

func testLaunchPerformance() throws {
    measure(metrics: [XCTApplicationLaunchMetric()]) {
        XCUIApplication().launch()
    }
}

func testScrollPerformance() throws {
    let app = XCUIApplication()
    app.launch()

    measure(metrics: [XCTOSSignpostMetric.scrollDecelerationMetric]) {
        app.tables.firstMatch.swipeUp()
    }
}
  1. CI Integration

    • Run performance tests in CI
    • Compare results to baseline
    • Fail build if regression > threshold
  2. Regression Analysis

    • When regression detected, profile locally
    • Use Time Profiler to find changed code
    • Optimize or adjust baseline if intentional

Baseline Format:

{
  "launch_time_ms": 350,
  "memory_mb": 120,
  "scroll_fps": 59,
  "thresholds": {
    "launch_time_ms": 450,
    "memory_mb": 150,
    "scroll_fps": 55
  }
}

Troubleshooting

High CPU Usage Causes

Symptoms:

  • App feels sluggish
  • Device gets hot
  • Battery drains quickly
  • Fans spin up (Mac Catalyst)

Common Causes:

1. Main Thread Blocking

// Problem: Heavy work on main thread
DispatchQueue.main.async {
    let result = expensiveCalculation() // Blocks UI
    updateUI(with: result)
}

// Solution: Move work off main thread
DispatchQueue.global(qos: .userInitiated).async {
    let result = expensiveCalculation()
    DispatchQueue.main.async {
        updateUI(with: result)
    }
}

2. Polling/Tight Loops

// Problem: Constant polling
Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { _ in
    checkForUpdates() // Called 100 times per second!
}

// Solution: Reasonable interval or event-driven
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
    checkForUpdates() // Called once per second
}

3. Inefficient Algorithms

// Problem: O(n²) complexity
for item in items {
    for other in items {
        compare(item, other) // n² comparisons
    }
}

// Solution: O(n log n) or O(n)
let sorted = items.sorted()
for (item, other) in zip(sorted, sorted.dropFirst()) {
    compare(item, other) // n comparisons
}

Memory Growth Patterns

Symptoms:

  • Memory usage increases over time
  • Memory warnings
  • App crashes after extended use

Common Patterns:

1. Unbounded Cache Growth

// Problem: Cache grows indefinitely
class ImageCache {
    private var cache: [URL: UIImage] = [:] // Never clears!
}

// Solution: Use NSCache (auto-eviction)
class ImageCache {
    private let cache = NSCache<NSURL, UIImage>()

    init() {
        cache.countLimit = 100 // Max 100 images
    }
}

2. Event Listener Accumulation

// Problem: Listeners never removed
override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(/* ... */) // Added every time!
}

// Solution: Remove in viewWillDisappear
override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}

3. Large Object Retention

// Problem: Keeping large objects in memory
class ViewController: UIViewController {
    var cachedImage: UIImage? // Large image retained
}

// Solution: Cache only when needed, clear when done
class ViewController: UIViewController {
    private var cachedImage: UIImage?

    override func didReceiveMemoryWarning() {
        cachedImage = nil // Release when memory pressure
    }
}

Network Inefficiencies

Symptoms:

  • Slow data loading
  • High data usage
  • Poor offline experience

Common Issues:

1. Waterfall Requests

// Problem: Sequential dependent requests
func loadProfile() async {
    let user = await fetchUser() // Wait...
    let posts = await fetchPosts(for: user) // Wait...
    let comments = await fetchComments(for: posts) // Wait...
}

// Solution: Parallel independent requests
func loadProfile() async {
    async let user = fetchUser()
    async let followers = fetchFollowers()
    async let settings = fetchSettings()

    let (u, f, s) = await (user, followers, settings)
}

2. No Request Deduplication

// Problem: Same request made multiple times
func loadData() {
    fetchUsers() // Request 1
    fetchUsers() // Request 2 (redundant!)
}

// Solution: Deduplicate requests
class APIClient {
    private var pendingRequests: [String: Task<Data, Error>] = [:]

    func fetch(url: String) async throws -> Data {
        if let pending = pendingRequests[url] {
            return try await pending.value // Reuse
        }

        let task = Task { try await URLSession.shared.data(from: URL(string: url)!) }
        pendingRequests[url] = task
        defer { pendingRequests[url] = nil }
        return try await task.value
    }
}

3. Large Uncompressed Payloads

// Problem: Sending/receiving uncompressed data
URLSession.shared.dataTask(with: url) // Default: no compression

// Solution: Enable compression
var request = URLRequest(url: url)
request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
URLSession.shared.dataTask(with: request)

Battery Drain Issues

Symptoms:

  • User complaints of battery drain
  • Device thermal throttling
  • High energy impact in Settings

Common Causes:

1. Excessive Background Activity

// Problem: Constant background work
func applicationDidEnterBackground(_ application: UIApplication) {
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
        syncData() // Drains battery in background
    }
}

// Solution: Use background tasks properly
func applicationDidEnterBackground(_ application: UIApplication) {
    let taskID = application.beginBackgroundTask {
        // Task expired, clean up
    }

    syncData {
        application.endBackgroundTask(taskID)
    }
}

2. Continuous Location Updates

// Problem: Always requesting location
locationManager.startUpdatingLocation() // Continuous GPS drain

// Solution: Use appropriate accuracy
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 100 // Update every 100m
locationManager.startMonitoringSignificantLocationChanges() // Low power mode

3. Rendering Offscreen Content

// Problem: Animating hidden views
override func viewDidDisappear(_ animated: Bool) {
    // Animations keep running! Wastes CPU/battery
}

// Solution: Pause animations when offscreen
override func viewDidDisappear(_ animated: Bool) {
    animationView.layer.pauseAnimations()
}

extension CALayer {
    func pauseAnimations() {
        let pausedTime = convertTime(CACurrentMediaTime(), from: nil)
        speed = 0.0
        timeOffset = pausedTime
    }
}

Best Practices

Profile on Device vs Simulator

Always profile on device for:

  • CPU performance (simulator uses Mac CPU)
  • Memory pressure (different memory characteristics)
  • Network latency (simulator uses Mac network)
  • Energy consumption (no battery in simulator)
  • GPU performance (different graphics hardware)

Simulator acceptable for:

  • Initial memory leak detection
  • Basic UI debugging
  • Quick iteration during development

Recommendation: Develop on simulator, validate on device, profile on device.

Release Configuration Profiling

Why Profile Release Builds:

  • Optimizations enabled: Swift optimizations, inlining, dead code elimination
  • Debug overhead removed: No assertions, no debug info
  • Represents production: Users run release builds

Debug vs Release Differences:

  • Release can be 5-10x faster
  • Memory patterns differ (ARC optimizations)
  • Some bugs only appear in release

How to Profile Release:

  1. Edit scheme → Run → Build Configuration → Release
  2. Enable "Debug executable" for debugging symbols
  3. Build and run
  4. Profile as normal

Warning: Some crashes only happen in release due to optimizations.

Continuous Performance Monitoring

Development Workflow:

  1. Baseline establishment: Profile app at start of sprint
  2. Feature development: Build features normally
  3. Pre-merge profiling: Profile before merging to main
  4. Regression check: Compare to baseline
  5. Optimization if needed: Fix regressions before merge

CI Integration:

# .github/workflows/performance.yml
name: Performance Tests

on: [pull_request]

jobs:
  performance:
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v2

      - name: Run performance tests
        run: xcodebuild test -scheme MyApp -destination 'platform=iOS Simulator,name=iPhone 15'

      - name: Check for regressions
        run: ./scripts/check_performance_baseline.sh

Automated Performance Tests:

class PerformanceTests: XCTestCase {
    func testLaunchPerformance() {
        measure(metrics: [XCTApplicationLaunchMetric()]) {
            XCUIApplication().launch()
        }
    }

    func testMemoryUsage() {
        let app = XCUIApplication()
        app.launch()

        measure(metrics: [XCTMemoryMetric()]) {
            // Perform memory-intensive operations
            for _ in 0..<100 {
                app.buttons["Load"].tap()
            }
        }
    }
}

Performance Budgets

Establish Budgets:

// PerformanceBudgets.swift
enum PerformanceBudget {
    static let launchTime: TimeInterval = 0.4 // 400ms
    static let memoryFootprint: Int = 150 * 1024 * 1024 // 150MB
    static let scrollFrameTime: TimeInterval = 0.0167 // 16.67ms (60 FPS)
    static let networkRequestTimeout: TimeInterval = 5.0 // 5s
}

// Enforce in tests
func testLaunchBudget() {
    let launchTime = measureLaunchTime()
    XCTAssertLessThan(launchTime, PerformanceBudget.launchTime,
                      "Launch time exceeded budget: \(launchTime)s > \(PerformanceBudget.launchTime)s")
}

Budget Categories:

Launch Time:

  • Critical: < 400ms (excellent)
  • Acceptable: 400-800ms (good)
  • Poor: > 800ms (needs optimization)

Memory:

  • Low-end devices: < 100MB
  • Mid-range devices: < 150MB
  • High-end devices: < 200MB

Frame Rate:

  • Scrolling: 60 FPS (16.67ms/frame)
  • Animations: 60 FPS
  • Acceptable: 50+ FPS

Network:

  • API response: < 1s
  • Image load: < 2s
  • Timeout: 5s max

Monitor Budgets:

  • Track metrics over time
  • Alert when budget exceeded
  • Review budgets quarterly

Integration with Xcode Workflows

This Skill integrates with xcode-workflows Skill:

Build for Profiling:

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Release",
  "destination": "platform=iOS,id=<device-udid>",
  "options": {
    "clean_before_build": true
  }
}

Archive for Profiling:

xcodebuild archive \
  -scheme MyApp \
  -configuration Release \
  -archivePath ./build/MyApp.xcarchive

Export for Profiling:

xcodebuild -exportArchive \
  -archivePath ./build/MyApp.xcarchive \
  -exportPath ./build \
  -exportOptionsPlist ExportOptions.plist

Related Skills

  • xcode-workflows: Building and configuring apps for profiling
  • crash-debugging: Analyzing performance-related crashes
  • ios-testing-patterns: Performance testing strategies

Related Resources

  • xc://operations/xcode: Xcodebuild operations for profiling builds
  • xc://reference/instruments: Complete Instruments template reference
  • xc://reference/performance-metrics: Key performance indicators and targets

Tip: Profile on device, use Release configuration, focus on user-impacting metrics first.

Simulator Workflows

Use the execute_simulator_command MCP tool for all simulator management

The xclaude-plugin provides the execute_simulator_command MCP tool which consolidates all simctl operations into a single, token-efficient dispatcher.

⚠️ CRITICAL: Always Use MCP Tools First

This is the most important rule: When working with iOS simulators, you MUST use the execute_simulator_command MCP tool.

  • ✅ DO: Invoke execute_simulator_command for all device/app lifecycle operations
  • ✅ DO: If the MCP tool fails, adjust parameters and retry
  • ✅ DO: Read error messages and debug the parameters
  • ❌ NEVER: Fall back to bash xcrun simctl commands
  • ❌ NEVER: Use simctl directly in bash
  • ❌ NEVER: Run xcrun simctl commands in a terminal

Why? The MCP tool provides:

  • Structured error handling
  • Token efficiency (consolidated into 1 tool vs. verbose bash output)
  • Proper integration with the xclaude-plugin architecture
  • Consistent response formatting

If execute_simulator_command fails, the issue is with parameters or device state - not that you should use bash.

When to Use Bash (And When NOT to)

❌ NEVER Use Bash For These (Use MCP Tools Instead)

Task❌ WRONG (Bash)✅ RIGHT (MCP Tool)
List devicesxcrun simctl listexecute_simulator_command op: "list"
Boot simulatorxcrun simctl boot <UDID>execute_simulator_command op: "device-lifecycle" sub: "boot"
Install appxcrun simctl install <UDID> <app.app>execute_simulator_command op: "app-lifecycle" sub: "install"
Launch appxcrun simctl launch <UDID> <bundle-id>execute_simulator_command op: "app-lifecycle" sub: "launch"
Screenshotxcrun simctl io <UDID> screenshotexecute_simulator_command op: "io" sub: "screenshot"

✅ Bash is Acceptable For (Non-Simulator Tasks)

  • File operations: mkdir, cp, rm, ls, etc.
  • Text inspection: grep, find, cat, etc.
  • Git operations: git status, git log, etc.
  • Environment checks: which, simctl --version, etc.
  • Project exploration: find . -name "*.app", etc.

The Rule: If it's about simulator management → Use MCP tool, not bash

Quick Reference

TaskMCP ToolOperationSub-Operation
List devicesexecute_simulator_commandlist-
Boot deviceexecute_simulator_commanddevice-lifecycleboot
Shutdown deviceexecute_simulator_commanddevice-lifecycleshutdown
Create deviceexecute_simulator_commanddevice-lifecyclecreate
Delete deviceexecute_simulator_commanddevice-lifecycledelete
Install appexecute_simulator_commandapp-lifecycleinstall
Launch appexecute_simulator_commandapp-lifecyclelaunch
Screenshotexecute_simulator_commandioscreenshot
Health checkexecute_simulator_commandhealth-check-

Device Management

1. Listing Devices - Use execute_simulator_command with operation: "list"

Invoke the execute_simulator_command MCP tool:

{
  "operation": "list"
}

Returns (Progressive Disclosure):

{
  "summary": {
    "total_devices": 47,
    "available_devices": 31,
    "booted_devices": 1
  },
  "booted": [
    {
      "name": "iPhone 15",
      "udid": "ABC123...",
      "state": "Booted",
      "runtime": "iOS 17.0"
    }
  ],
  "cache_id": "sim-list-xyz789",
  "next_steps": [
    "Use device name or UDID for operations",
    "Query cache_id for full device list if needed"
  ]
}

Note: Large device lists use progressive disclosure to save tokens.

2. Booting a Simulator - Use execute_simulator_command with device-lifecycle

Invoke the execute_simulator_command MCP tool:

By Name:

{
  "operation": "device-lifecycle",
  "sub_operation": "boot",
  "device_id": "iPhone 15"
}

By UDID:

{
  "operation": "device-lifecycle",
  "sub_operation": "boot",
  "device_id": "ABC123-DEF456-...",
  "parameters": {
    "wait_for_boot": true
  }
}

wait_for_boot: Blocks until device fully booted (recommended)

3. Shutting Down

{
  "operation": "device-lifecycle",
  "sub_operation": "shutdown",
  "device_id": "iPhone 15"
}

4. Creating a New Simulator

{
  "operation": "device-lifecycle",
  "sub_operation": "create",
  "device_id": "My iPhone 15 Test",
  "parameters": {
    "device_type": "iPhone 15",
    "runtime": "iOS 17.0"
  }
}

Returns: New device UDID

Available Device Types:

  • iPhone SE (3rd generation)
  • iPhone 14, 14 Plus, 14 Pro, 14 Pro Max
  • iPhone 15, 15 Plus, 15 Pro, 15 Pro Max
  • iPad (10th generation), iPad Air, iPad Pro

Check available runtimes: Use list to see installed iOS versions

5. Deleting a Simulator

{
  "operation": "device-lifecycle",
  "sub_operation": "delete",
  "device_id": "My iPhone 15 Test"
}

Warning: This is permanent and cannot be undone.

6. Erasing a Simulator

Remove all data but keep device:

{
  "operation": "device-lifecycle",
  "sub_operation": "erase",
  "device_id": "iPhone 15"
}

When to erase:

  • Reset app state completely
  • Clear test data
  • Reproduce fresh install behavior

7. Cloning a Simulator

Duplicate a device with all its data:

{
  "operation": "device-lifecycle",
  "sub_operation": "clone",
  "device_id": "iPhone 15",
  "parameters": {
    "new_name": "iPhone 15 Clone"
  }
}

Use case: Preserve a specific test state

App Management

1. Installing an App

{
  "operation": "app-lifecycle",
  "sub_operation": "install",
  "device_id": "iPhone 15",
  "app_identifier": "/path/to/MyApp.app"
}

Note: app_identifier is the path to .app bundle for install operation.

Build + Install Pattern:

1. execute_xcode_command (operation: build) → Get .app path
2. execute_simulator_command (operation: app-lifecycle, sub_operation: install)

2. Launching an App

{
  "operation": "app-lifecycle",
  "sub_operation": "launch",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp"
}

With Arguments:

{
  "operation": "app-lifecycle",
  "sub_operation": "launch",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp",
  "parameters": {
    "arguments": ["--test-mode", "--mock-data"],
    "environment": {
      "API_URL": "https://staging.example.com"
    }
  }
}

3. Terminating an App

{
  "operation": "app-lifecycle",
  "sub_operation": "terminate",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp"
}

4. Uninstalling an App

{
  "operation": "app-lifecycle",
  "sub_operation": "uninstall",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp"
}

5. Getting App Container Paths

For accessing app data:

{
  "operation": "get-app-container",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp",
  "parameters": {
    "container_type": "data"
  }
}

Container Types:

  • data: App's Documents, Library, tmp directories
  • bundle: App's .app bundle
  • group: Shared group containers

Returns: File system path to container

Use case: Inspect database files, logs, or user defaults

Capture & Media

1. Taking Screenshots

{
  "operation": "io",
  "sub_operation": "screenshot",
  "device_id": "iPhone 15",
  "parameters": {
    "output_path": "/path/to/screenshot.png"
  }
}

Auto-generated path: If output_path omitted, creates temp file

2. Recording Video

{
  "operation": "io",
  "sub_operation": "video",
  "device_id": "iPhone 15",
  "parameters": {
    "output_path": "/path/to/video.mp4",
    "duration": 30
  }
}

Note: Duration in seconds. Press Ctrl+C to stop recording manually.

Advanced Operations

1. Opening URLs

{
  "operation": "openurl",
  "device_id": "iPhone 15",
  "parameters": {
    "url": "myapp://deep-link/path"
  }
}

Use cases:

  • Test universal links
  • Test deep linking
  • Open Safari to specific URL

2. Push Notifications

{
  "operation": "push",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp",
  "parameters": {
    "payload": {
      "aps": {
        "alert": "Test notification",
        "badge": 1,
        "sound": "default"
      }
    }
  }
}

Payload: Standard APNs JSON payload

Environment Validation

Health Check

Verify iOS development environment:

{
  "operation": "health-check"
}

Checks:

  • Xcode installation
  • Command line tools
  • simctl availability
  • CoreSimulator framework

Returns:

{
  "xcode_installed": true,
  "xcode_version": "15.0",
  "simctl_available": true,
  "issues": []
}

Device Selection Strategies

By Name (Easiest)

{
  "device_id": "iPhone 15"
}

Pro: Readable, easy to remember Con: May match multiple devices

By UDID (Most Reliable)

{
  "device_id": "ABC123-DEF456-GHI789..."
}

Pro: Unique, guaranteed single match Con: Long, hard to remember

Using "booted" (Convenience)

Some tools (like IDB) accept "booted" to target the currently booted simulator:

{
  "target": "booted"
}

Note: Only works with IDB operations, not simctl

Common Workflows

Workflow: Fresh Install Test

1. boot → Start simulator
2. uninstall → Remove existing app
3. install → Install fresh build
4. launch → Start app
5. (UI automation) → Test flow
6. terminate → Stop app
7. shutdown → Stop simulator

Workflow: Rapid Iteration

1. build → Compile latest code
2. install → Update app on simulator (already booted)
3. terminate → Stop running app
4. launch → Start updated app

Note: No need to boot/shutdown between iterations

Workflow: Multi-Device Testing

1. list → Get available devices
2. For each device:
   - boot → Start device
   - install → Install app
   - launch → Start app
   - (run tests) → Execute test suite
   - terminate → Stop app
   - shutdown → Stop device

Troubleshooting

Device Not Found

Problem: "Unable to find device: iPhone 15"

Solutions:

  1. Run list to see exact device names
  2. Use UDID instead of name
  3. Check device hasn't been deleted

Unable to Boot

Problem: Boot fails or times out

Solutions:

  1. Check disk space (simulators need space)
  2. Shutdown other running simulators
  3. Restart CoreSimulator: killall -9 com.apple.CoreSimulator.CoreSimulatorService
  4. Run health-check to validate environment

App Install Fails

Problem: Install operation fails

Solutions:

  1. Verify .app path is correct
  2. Check device is booted
  3. Ensure .app is built for simulator (not device)
  4. Try erasing simulator first

App Won't Launch

Problem: Launch succeeds but app crashes immediately

Solutions:

  1. Check app logs in Console.app
  2. Verify app is signed correctly
  3. Check for missing frameworks/resources
  4. Try clean build + reinstall

Performance Tips

1. Keep Simulators Booted

Booting is slow (~5-10 seconds). Keep simulator running during development.

2. Use Progressive Disclosure

Device lists can be large. Summary provides what you need 95% of the time.

3. Reuse Simulators

Creating/deleting is slower than erasing. Reuse devices when possible.

4. Parallel Operations

Boot multiple simulators in parallel for multi-device testing:

Launch 3 boot operations concurrently
Wait for all to complete
Proceed with testing

Integration with Other Tools

With Xcodebuild

1. execute_xcode_command (build) → Get .app bundle
2. execute_simulator_command (install) → Install to simulator
3. execute_simulator_command (launch) → Start app

With IDB

1. execute_simulator_command (boot) → Start device
2. execute_idb_command (describe) → Query UI
3. execute_idb_command (tap) → Interact

With Testing

1. execute_simulator_command (boot) → Start device
2. execute_xcode_command (test) → Run tests on device
3. execute_simulator_command (shutdown) → Stop device

Integration with MCP Tools

This Skill works with execute_simulator_command tool:

  • All operations use the execute_simulator_command tool
  • Tool handles simctl execution
  • Tool provides progressive disclosure for large outputs
  • This Skill teaches WHEN and HOW to use operations

Related Skills

  • xcode-workflows: Building apps for simulators
  • ui-automation-workflows: Automating simulator interactions
  • ios-testing-patterns: Test execution strategies

Related Resources

  • xc://operations/simulator: Complete simctl operations reference
  • xc://reference/device-specs: Available device types and runtimes
  • xc://reference/error-codes: Common simulator errors

Tip: Use list to discover, boot by name for convenience, use UDID for reliability.

State Management Skill

Optimizing token efficiency and state management in xc-plugin

Overview

The xc-plugin implements sophisticated state management through caching, progressive disclosure, and configuration management. This Skill teaches how to leverage these patterns to minimize token usage, improve performance, and maintain clean state across operations.

Key Benefits:

  • 85-90% token reduction through progressive disclosure
  • Cache-friendly operations avoid redundant work
  • Deterministic state ensures reliable test results
  • Configuration consistency across development workflows

When to Use This Skill

Use this Skill when you need to:

  1. Optimize Token Usage

    • Working with large device lists or build logs
    • Reducing context window consumption
    • Implementing efficient query patterns
  2. Manage Cache State

    • Understanding when responses are cached
    • Invalidating stale cache entries
    • Querying cached data efficiently
  3. Handle Configuration

    • Setting up consistent build environments
    • Managing simulator preferences
    • Configuring test execution parameters
  4. Design Efficient Workflows

    • Implementing progressive disclosure patterns
    • Avoiding expensive repeated operations
    • Building cache-aware automation

Key Concepts

Progressive Disclosure Pattern

Principle: Show essentials first, provide details on-demand.

Instead of returning massive datasets that consume tokens, xc-plugin returns:

  1. Summary - Key metrics and booted devices (~100 tokens)
  2. cache_id - Reference to full dataset
  3. Follow-up query - Retrieve complete details only if needed

Token Efficiency:

Traditional approach: 2000 tokens (full device list)
Progressive disclosure: 100 tokens (summary) + optional 2000 tokens (details)
Average savings: 95% (most queries don't need full details)

Cache Architecture

The plugin uses deterministic caching for expensive operations:

Cache Key Generation:

  • SHA-256 hash of operation + parameters
  • First 16 characters used as cache_id
  • Deterministic: Same input → Same cache_id

Cache Storage:

  • In-memory for current session
  • Optional disk persistence
  • Automatic expiration (configurable TTL)

Cache-Friendly Operations:

  • list operations (device lists, app lists)
  • build operations (build logs, test results)
  • describe operations (accessibility trees)

Response Types

SuccessResult with Progressive Disclosure:

{
  success: true,
  data: {
    summary: "31 devices available, 1 booted",
    booted_devices: [...],
    cache_id: "a1b2c3d4e5f6g7h8"
  },
  summary: "Device list retrieved successfully"
}

Follow-up Query Pattern:

{
  operation: "get-details",
  cache_id: "a1b2c3d4e5f6g7h8",
  detail_type: "full-list"
}

Workflows

Workflow 1: Cache-Aware Device Listing

Initial Query (Token-Efficient):

{
  "operation": "list",
  "parameters": {
    "concise": true
  }
}

Response:

{
  "success": true,
  "data": {
    "summary": {
      "total_devices": 47,
      "available_devices": 31,
      "booted_devices": 1
    },
    "booted": [
      {
        "name": "iPhone 15",
        "udid": "ABC123...",
        "state": "Booted",
        "runtime": "iOS 17.0"
      }
    ],
    "cache_id": "sim-list-xyz789"
  }
}

Follow-Up (Only If Needed):

{
  "operation": "get-details",
  "cache_id": "sim-list-xyz789",
  "detail_type": "full-list"
}

Token Analysis:

  • Initial query: ~150 tokens
  • Follow-up (if needed): ~2000 tokens
  • Traditional approach: ~2000 tokens always
  • Savings: 92% when details not needed

Workflow 2: Build Cache Management

Build Operation:

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Debug",
  "output_format": "summary"
}

Response with Cache:

{
  "success": true,
  "data": {
    "message": "Build succeeded",
    "build_time": "45.2s",
    "warnings": 3,
    "cache_id": "build-abc123"
  },
  "summary": "Build completed successfully with 3 warnings"
}

Retrieve Full Logs:

{
  "operation": "get-details",
  "cache_id": "build-abc123",
  "detail_type": "full-log"
}

Cache Invalidation Scenarios:

  • Source code changes
  • Scheme configuration changes
  • Clean operation executed
  • Manual cache clear

Workflow 3: Configuration State Management

Query Current Configuration:

{
  "operation": "cache",
  "sub_operation": "get-config"
}

Response:

{
  "cache_enabled": true,
  "cache_ttl": 3600,
  "max_cache_size": 100,
  "persistence_enabled": false
}

Update Configuration:

{
  "operation": "cache",
  "sub_operation": "set-config",
  "parameters": {
    "cache_ttl": 7200,
    "persistence_enabled": true
  }
}

Workflow 4: State Cleanup Between Tests

Pattern for Clean Test State:

1. cache (clear: "all") → Remove all cached data
2. device-lifecycle (erase) → Reset simulator state
3. app-lifecycle (uninstall) → Remove app
4. app-lifecycle (install) → Fresh install
5. app-lifecycle (launch) → Start with clean state
6. (run tests) → Execute test suite
7. cache (clear: "response") → Clean response cache

Why This Matters:

  • Eliminates test interdependencies
  • Prevents cache poisoning
  • Ensures reproducible results
  • Catches state-dependent bugs

Progressive Disclosure Pattern

Pattern Structure

Level 1: Summary (Always Returned)

{
  "summary": {
    "key_metric_1": "value",
    "key_metric_2": "value",
    "action_taken": "description"
  },
  "cache_id": "unique-identifier",
  "next_steps": [
    "Suggested action 1",
    "Suggested action 2"
  ]
}

Level 2: Detailed Query (On-Demand)

{
  "operation": "get-details",
  "cache_id": "unique-identifier",
  "detail_type": "full-data|errors-only|warnings-only|metadata"
}

When to Use Progressive Disclosure

Always Use For:

  • Device lists (>5 devices)
  • Build logs (>100 lines)
  • Test results (>10 tests)
  • Accessibility trees (>20 elements)
  • App lists (>10 apps)

Skip For:

  • Single device operations
  • Error messages
  • Quick status checks
  • Configuration queries

Example: Test Results

Summary Response:

{
  "success": false,
  "data": {
    "tests_run": 45,
    "tests_passed": 43,
    "tests_failed": 2,
    "failed_tests": [
      "MyAppTests.LoginTests.testInvalidPassword",
      "MyAppTests.LoginTests.testEmptyCredentials"
    ],
    "cache_id": "test-run-def456"
  }
}

Full Details Query:

{
  "operation": "get-details",
  "cache_id": "test-run-def456",
  "detail_type": "full-log"
}

Token Efficiency:

  • Summary: ~200 tokens
  • Full log: ~3000 tokens
  • Savings: 93% for typical success cases

Caching Strategies

Cache-Friendly Operations

High Cache Value (Long TTL):

  • list operations (device list changes infrequently)
  • version operations (Xcode version is stable)
  • show-build-settings (project config changes rarely)

Moderate Cache Value (Medium TTL):

  • build operations (results valid until code changes)
  • test operations (results valid until code/tests change)
  • describe operations (UI state changes moderately)

Low Cache Value (Short TTL):

  • device-lifecycle (device state changes frequently)
  • app-lifecycle (app state is dynamic)
  • input/tap operations (UI interactions modify state)

Cache TTL Guidelines

// Recommended TTL values
{
  simulator_list: 1800,      // 30 minutes
  device_state: 60,          // 1 minute
  build_results: 3600,       // 1 hour
  test_results: 3600,        // 1 hour
  xcode_version: 86400,      // 24 hours
  project_schemes: 3600,     // 1 hour
  accessibility_tree: 10     // 10 seconds
}

Cache Invalidation Triggers

Automatic Invalidation:

  • TTL expiration
  • Memory pressure (LRU eviction)
  • Conflicting operation (e.g., clean invalidates build cache)

Manual Invalidation:

{
  "operation": "cache",
  "sub_operation": "clear",
  "parameters": {
    "cache_type": "simulator|project|response|all"
  }
}

Smart Invalidation:

  • File modification detection (build cache)
  • State change detection (device cache)
  • Operation sequence analysis (test cache)

Memory vs Disk Caching

In-Memory Cache (Default):

  • Pros: Fast access, no I/O overhead
  • Cons: Lost on process restart
  • Use For: Session-scoped data, frequently accessed data

Disk Cache (Optional):

  • Pros: Persists across restarts, larger capacity
  • Cons: I/O overhead, synchronization complexity
  • Use For: Build artifacts, test results, expensive queries

Enable Disk Persistence:

{
  "operation": "persistence",
  "sub_operation": "enable",
  "parameters": {
    "cache_dir": "/tmp/xc-cache"
  }
}

Configuration Management

Xcode Preferences

Query Build Settings:

{
  "operation": "show-build-settings",
  "scheme": "MyApp",
  "configuration": "Debug"
}

Common Settings to Cache:

  • PRODUCT_BUNDLE_IDENTIFIER
  • DEVELOPMENT_TEAM
  • CODE_SIGN_IDENTITY
  • SDKROOT
  • ARCHS

Use Case:

  • Validate configuration consistency
  • Debug build issues
  • Generate documentation
  • Audit security settings

Simulator Settings

Query Simulator Configuration:

{
  "operation": "list",
  "parameters": {
    "runtime": "iOS 17.0",
    "device_type": "iPhone"
  }
}

Persist Simulator State:

  • Boot order (preferred device)
  • Location simulation settings
  • Accessibility preferences
  • Network conditions

Build Configurations

Debug vs Release Configuration:

Debug:

{
  "configuration": "Debug",
  "options": {
    "parallel": true,
    "quiet": false
  }
}
  • Optimizations: Off
  • Symbols: Included
  • Token Impact: Verbose logs (~2000 tokens)
  • Cache Strategy: Short TTL (code changes frequently)

Release:

{
  "configuration": "Release",
  "options": {
    "parallel": true,
    "quiet": true
  }
}
  • Optimizations: On
  • Symbols: Optional
  • Token Impact: Quiet logs (~300 tokens)
  • Cache Strategy: Long TTL (less frequent)

Environment Variables

Set Test Environment:

{
  "operation": "app-lifecycle",
  "sub_operation": "launch",
  "device_id": "iPhone 15",
  "app_identifier": "com.example.MyApp",
  "parameters": {
    "environment": {
      "API_URL": "https://staging.example.com",
      "MOCK_DATA": "true",
      "LOG_LEVEL": "debug"
    }
  }
}

Common Environment Variables:

  • API_URL - Backend endpoint
  • FEATURE_FLAGS - Enable/disable features
  • TEST_MODE - Testing-specific behavior
  • LOG_LEVEL - Logging verbosity

Best Practices

1. Minimize Context Window Usage

Use Progressive Disclosure:

// Good: Request summary first
{
  "operation": "list",
  "parameters": { "concise": true }
}

// Then query details only if needed
{
  "operation": "get-details",
  "cache_id": "sim-list-xyz"
}

Avoid Verbose Operations:

// Bad: Always verbose
{
  "operation": "build",
  "options": { "verbose": true }
}

// Good: Quiet by default, verbose on errors
{
  "operation": "build",
  "options": { "quiet": true }
}

2. Cache Expensive Operations

Identify Expensive Operations:

  • build (20-120 seconds)
  • test (10-300 seconds)
  • list with large device sets (1-5 seconds)
  • describe with complex UI (0.5-2 seconds)

Cache Strategy:

// First call: Execute and cache
{
  "operation": "list"
}
// Response includes cache_id

// Subsequent calls: Use cached data
{
  "operation": "get-details",
  "cache_id": "previous-cache-id"
}

3. Clear State Between Test Runs

Clean State Pattern:

1. Cache clear (all)
2. Simulator erase
3. App uninstall
4. Fresh app install
5. Launch with test environment
6. Run tests
7. Cache clear (response)

Why Each Step:

  • Cache clear: No stale data influencing tests
  • Simulator erase: Clean device state
  • App uninstall: Remove app data/preferences
  • Fresh install: Simulate first-time user
  • Test environment: Consistent configuration
  • Response cache clear: Clean logs for next run

4. Handle Stale Cache Gracefully

Detect Stale Cache:

// Check cache timestamp
if (cache_age > ttl) {
  invalidateCache(cache_id);
  refetch();
}

Recovery Strategy:

// If cache miss or stale:
{
  "operation": "original-operation",
  // Original parameters
}
// Plugin automatically refreshes cache

User Pattern:

  • Try cached query first
  • If data seems stale, force refresh
  • Update cache with new results

5. Token Efficiency Metrics

Track Token Usage:

Summary responses: ~100-300 tokens
Full responses: ~1000-5000 tokens
Progressive disclosure savings: 80-95%

Optimization Checklist:

  • Use concise: true for list operations
  • Request summary output format for builds
  • Query cache_id before full details
  • Use quiet: true for non-debug builds
  • Enable response caching for repeated queries

6. Configuration File Examples

Build Configuration:

{
  "scheme": "MyApp",
  "configurations": {
    "debug": {
      "configuration": "Debug",
      "destination": "platform=iOS Simulator,name=iPhone 15",
      "cache_strategy": "short_ttl",
      "output_format": "summary"
    },
    "release": {
      "configuration": "Release",
      "destination": "generic/platform=iOS",
      "cache_strategy": "long_ttl",
      "output_format": "detailed"
    }
  }
}

Test Configuration:

{
  "test_scheme": "MyAppTests",
  "test_devices": [
    "iPhone 15",
    "iPad Pro (12.9-inch)"
  ],
  "clean_state": true,
  "cache_results": true,
  "parallel_execution": false,
  "environment": {
    "TEST_MODE": "true",
    "MOCK_NETWORK": "true"
  }
}

Cache Configuration:

{
  "cache": {
    "enabled": true,
    "ttl": {
      "simulator_list": 1800,
      "build_results": 3600,
      "test_results": 3600,
      "device_state": 60
    },
    "persistence": {
      "enabled": true,
      "path": "/tmp/xc-cache",
      "max_size_mb": 500
    },
    "invalidation": {
      "auto_invalidate_on_build": true,
      "auto_invalidate_on_test": false
    }
  }
}

Integration with MCP Tools

This Skill applies to all xc-plugin MCP tools:

Cache-Aware Tools:

  • xcodebuild-list - Returns cache_id for project data
  • xcodebuild-build - Returns cache_id for build logs
  • xcodebuild-test - Returns cache_id for test results
  • simctl-list - Returns cache_id for device lists
  • idb-ui-describe - Returns cache_id for UI trees

Cache Management Tools:

  • xcodebuild-get-details - Query cached build data
  • simctl-get-details - Query cached simulator data
  • cache - Manage cache configuration
  • persistence - Configure disk caching

Related Skills

  • simulator-workflows: Device management operations
  • xcode-workflows: Build system operations
  • ui-automation-workflows: Accessibility tree caching
  • ios-testing-patterns: Test state management

Related Resources

  • xc://reference/cache-architecture - Cache implementation details
  • xc://reference/token-optimization - Token efficiency guide
  • xc://workflows/progressive-disclosure - Pattern documentation
  • xc://reference/configuration - Configuration reference

Remember: Progressive disclosure first, full details only when needed. Cache expensive operations. Clear state between tests. 85-90% token savings are achievable with proper state management.

UI Automation Workflows

Use the execute_idb_command MCP tool for all UI automation

The xclaude-plugin provides the execute_idb_command MCP tool which consolidates all IDB UI automation operations into a single, token-efficient dispatcher.

⚠️ CRITICAL: Always Use MCP Tools First

This is the most important rule: When automating UI interactions, you MUST use the execute_idb_command MCP tool.

  • ✅ DO: Invoke execute_idb_command for all UI automation, element finding, and accessibility queries
  • ✅ DO: If the MCP tool fails, adjust parameters and retry
  • ✅ DO: Read error messages and debug the parameters
  • ❌ NEVER: Fall back to bash idb commands
  • ❌ NEVER: Use idb directly in bash
  • ❌ NEVER: Run idb commands in a terminal

Why? The MCP tool provides:

  • Structured error handling
  • Token efficiency (consolidated into 1 tool vs. verbose bash output)
  • Proper integration with the xclaude-plugin architecture
  • Accessibility-first patterns built-in

If execute_idb_command fails, the issue is with parameters or app state - not that you should use bash.

Core Principle: Accessibility Before Screenshots

Always query the accessibility tree first. Only use screenshots as a fallback.

Use the execute_idb_command MCP tool with operation describe to access the accessibility tree.

Why Accessibility-First?

ApproachTimeTokensReliability
Accessibility tree~120ms~50Survives theme changes
Screenshot~2000ms~170Breaks on visual changes

Result: 3-4x faster, 80% cheaper, more reliable

Standard Workflow

1. Check Accessibility Quality (Optional) - Use execute_idb_command

Before starting automation, check if the app has good accessibility support:

Invoke the execute_idb_command MCP tool:

{
  "operation": "check-accessibility",
  "target": "booted"
}

Interprets:

  • "excellent" or "good": Proceed with accessibility-first workflow
  • "poor" or "insufficient": May need to rely more on screenshots

Note: Most modern iOS apps have good accessibility support. Skip this check if you're confident.

2. Query Accessibility Tree - Use execute_idb_command with operation: "describe"

This is your starting point for all UI automation:

Invoke the execute_idb_command MCP tool:

{
  "operation": "describe",
  "target": "booted",
  "parameters": {
    "operation": "all"
  }
}

Returns:

{
  "elements": [
    {
      "label": "Login",
      "type": "Button",
      "frame": { "x": 100, "y": 400, "width": 175, "height": 50 },
      "centerX": 187,
      "centerY": 425,
      "enabled": true,
      "visible": true
    },
    {
      "label": "Email",
      "type": "TextField",
      "value": "",
      "frame": { "x": 50, "y": 300, "width": 275, "height": 44 },
      "centerX": 187,
      "centerY": 322
    }
  ]
}

Use centerX and centerY for tap coordinates.

3. Find Your Element

Option A: Search by Label/Text (Preferred)

{
  "operation": "find-element",
  "target": "booted",
  "parameters": {
    "query": "Login"
  }
}

Option B: Manual Search

From the accessibility tree response, find the element you want by:

  • label: Button text, field labels
  • type: Button, TextField, Cell, etc.
  • value: Current input value
  • visible: Only interact with visible elements

4. Interact with Element

Tap:

{
  "operation": "tap",
  "target": "booted",
  "parameters": {
    "x": 187,
    "y": 425
  }
}

Input Text:

{
  "operation": "input",
  "target": "booted",
  "parameters": {
    "text": "user@example.com"
  }
}

Keyboard Actions:

{
  "operation": "input",
  "target": "booted",
  "parameters": {
    "key": "return"
  }
}

Available keys: return, home, delete, space, escape, tab, up, down, left, right

5. Verify State

After interaction, query accessibility tree again to verify:

{
  "operation": "describe",
  "target": "booted"
}

Common Patterns

Pattern: Login Flow

1. describe → Find "Email" text field
2. tap → Focus email field
3. input → Type email
4. describe → Find "Password" text field
5. tap → Focus password field
6. input → Type password
7. describe → Find "Login" button
8. tap → Submit form
9. describe → Verify next screen

Pattern: Navigate and Tap

1. describe → Get all buttons
2. find-element → Search for specific button
3. tap → Execute tap
4. describe → Verify navigation

Pattern: Fill Form

1. describe → Get all text fields
2. For each field:
   - tap → Focus field
   - input → Enter text
   - input key:return → Next field
3. describe → Find submit button
4. tap → Submit

Pattern: Scroll and Find

1. describe → Check if element visible
2. If not visible:
   - gesture (swipe up) → Scroll
   - describe → Check again
3. find-element → Locate target
4. tap → Interact

Gestures

Swipe

{
  "operation": "gesture",
  "target": "booted",
  "parameters": {
    "gesture_type": "swipe",
    "direction": "up",
    "duration": 200
  }
}

Directions: up, down, left, right

Button Presses

{
  "operation": "gesture",
  "target": "booted",
  "parameters": {
    "gesture_type": "button",
    "button": "HOME"
  }
}

Buttons: HOME, LOCK, SIRI, SIDE_BUTTON, APPLE_PAY, SCREENSHOT, APP_SWITCH

When to Use Screenshots (Fallback Only)

Only use screenshots if:

  1. Accessibility quality is "poor"

    { "operation": "check-accessibility", "target": "booted" }
    
  2. Visual verification needed

    • Checking UI layout
    • Verifying colors/images
    • Debug visual issues
  3. Element not in accessibility tree

    • Custom drawn UI
    • Canvas/game elements
    • Some third-party components

For everything else, use accessibility tree.

Troubleshooting

Element Not Found

Problem: find-element returns no results

Solutions:

  1. Query full tree with describe to see all elements
  2. Check if element is in a scroll view (may be off-screen)
  3. Verify app state (correct screen?)
  4. Check if element has accessibility label

Tap Not Working

Problem: Tap executes but nothing happens

Solutions:

  1. Verify element is enabled: true
  2. Check element is visible: true
  3. Confirm coordinates are correct (use centerX, centerY)
  4. Element might need double-tap or long-press

Input Not Working

Problem: Text input not appearing

Solutions:

  1. Tap text field first to focus
  2. Wait for keyboard to appear
  3. Check field is not disabled
  4. Use keyboard-specific keys (return, delete)

Advanced: Coordinate Transformation

If using screenshots with idb-ui-tap, coordinates may need scaling:

{
  "operation": "tap",
  "target": "booted",
  "parameters": {
    "x": 187,
    "y": 425,
    "applyScreenshotScale": true,
    "screenshotScaleX": 0.5,
    "screenshotScaleY": 0.5
  }
}

But with accessibility-first, this is rarely needed.

Performance Tips

  1. Batch Operations: Group describe queries to minimize round-trips
  2. Cache Tree: Reuse accessibility tree if UI hasn't changed
  3. Target Specific Areas: Use describe with point coordinates for specific regions
  4. Avoid Unnecessary Waits: Accessibility tree reflects real-time state

Integration with MCP Tools

This Skill works with execute_idb_command tool:

  • All operations use the execute_idb_command tool
  • Tool handles IDB connection and execution
  • Tool returns structured accessibility data
  • This Skill teaches WHEN and HOW to use operations

Related Skills

  • accessibility-testing: WCAG compliance and quality assessment
  • ios-testing-patterns: Test automation strategies
  • simulator-workflows: Device and app management

Related Resources

  • xc://operations/idb: Complete IDB operations reference
  • xc://reference/accessibility: Accessibility tree structure guide
  • xc://workflows/accessibility-first: This workflow pattern

Remember: Accessibility tree first, screenshots last. 3-4x faster, 80% cheaper.

Xcode Workflows

Use the execute_xcode_command MCP tool for all iOS build operations

The xclaude-plugin provides the execute_xcode_command MCP tool which consolidates all xcodebuild operations into a single, token-efficient dispatcher.

⚠️ CRITICAL: Always Use MCP Tools First

This is the most important rule: When working with iOS builds, you MUST use the execute_xcode_command MCP tool.

  • ✅ DO: Invoke execute_xcode_command for all build/test/clean operations
  • ✅ DO: If the MCP tool fails, adjust parameters and retry
  • ✅ DO: Read error messages and debug the parameters
  • ❌ NEVER: Fall back to bash xcodebuild commands
  • ❌ NEVER: Use xcodebuild directly in bash
  • ❌ NEVER: Run xcrun xcodebuild in a terminal

Why? The MCP tool provides:

  • Structured error handling
  • Token efficiency (consolidated into 1 tool vs. verbose bash output)
  • Proper integration with the xclaude-plugin architecture
  • Consistent response formatting

If execute_xcode_command fails, the issue is with parameters or the project - not that you should use bash.

When to Use Bash (And When NOT to)

❌ NEVER Use Bash For These (Use MCP Tools Instead)

Task❌ WRONG (Bash)✅ RIGHT (MCP Tool)
List schemesxcodebuild -listexecute_xcode_command op: "list"
Build appxcodebuild -scheme...execute_xcode_command op: "build"
Run testsxcodebuild -scheme... testexecute_xcode_command op: "test"
Clean buildxcodebuild cleanexecute_xcode_command op: "clean"
Get Xcode infoxcodebuild -versionexecute_xcode_command op: "version"

✅ Bash is Acceptable For (Non-Build Tasks)

  • File operations: mkdir, cp, rm, ls, etc.
  • Text inspection: grep, find, cat, etc.
  • Git operations: git status, git log, etc.
  • Environment checks: which, xcode-select --version, etc.
  • Project exploration: find . -name "*.swift", etc.

The Rule: If it's about Xcode building/testing → Use MCP tool, not bash

Quick Reference

TaskMCP ToolOperationKey Parameters
Build for simulatorexecute_xcode_commandbuildscheme, configuration:Debug
Build for deviceexecute_xcode_commandbuildscheme, configuration:Release, destination
Run testsexecute_xcode_commandtestscheme, destination
Clean buildexecute_xcode_commandcleanscheme
List schemesexecute_xcode_commandlist-
Get Xcode infoexecute_xcode_commandversion-

Standard Workflows

1. Building an App

Step 1: Discover Schemes - Use execute_xcode_command with operation: "list"

Invoke the execute_xcode_command MCP tool:

{
  "operation": "list",
  "project_path": "/path/to/Project.xcodeproj"
}

Note: project_path is optional - auto-detected from current directory.

Returns:

{
  "schemes": ["MyApp", "MyAppTests", "MyAppUITests"],
  "targets": ["MyApp", "MyAppKit", "MyAppTests"]
}

Step 2: Build - Use execute_xcode_command with operation: "build"

Invoke the execute_xcode_command MCP tool with build parameters:

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Debug",
  "destination": "platform=iOS Simulator,name=iPhone 15"
}

Common Destinations:

  • iOS Simulator (explicit - recommended): "platform=iOS Simulator,name=iPhone 15,OS=18.0"
  • iOS Simulator (auto-resolve): "platform=iOS Simulator,name=iPhone 15" (will auto-detect latest OS)
  • iOS Device: "platform=iOS,id=<device-udid>"
  • Any Simulator: "platform=iOS Simulator,name=Any iOS Simulator Device"
  • macOS: "platform=macOS"

Note: The destination parameter now supports auto-resolution! If you omit the OS version, the tool will automatically query available simulators and select the latest OS version for the specified device name. For explicit control, include the OS version in your destination string.

2. Running Tests

Unit Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15"
}

Specific Test Plan:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "test_plan": "UnitTests"
  }
}

Run Specific Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "only_testing": [
      "MyAppTests/LoginTests/testSuccessfulLogin",
      "MyAppTests/LoginTests/testInvalidCredentials"
    ]
  }
}

Skip Specific Tests:

{
  "operation": "test",
  "scheme": "MyApp",
  "destination": "platform=iOS Simulator,name=iPhone 15",
  "options": {
    "skip_testing": ["MyAppUITests"]
  }
}

3. Clean Build

When to Clean:

  • Build artifacts corrupted
  • Switching branches significantly
  • Mysterious build failures
  • Before release builds
{
  "operation": "clean",
  "scheme": "MyApp"
}

Clean + Build Pattern:

{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Debug",
  "options": {
    "clean_before_build": true
  }
}

Configurations

Debug vs Release

Debug (Default):

  • Optimizations disabled
  • Debug symbols included
  • Faster compile time
  • Larger binary
  • Use for: Development, testing

Release:

  • Optimizations enabled
  • Debug symbols optional
  • Slower compile time
  • Smaller binary
  • Use for: Production, App Store, performance testing
{
  "operation": "build",
  "scheme": "MyApp",
  "configuration": "Release"
}

Build Options

Common Options

{
  "operation": "build",
  "scheme": "MyApp",
  "options": {
    "clean_before_build": true,
    "parallel": true,
    "sdk": "iphoneos17.0",
    "arch": "arm64",
    "quiet": false
  }
}

Options Explained:

  • clean_before_build: Clean before building (ensures fresh build)
  • parallel: Enable parallel builds (faster on multi-core)
  • sdk: Specific SDK version (usually auto-selected)
  • arch: Target architecture (arm64 for devices, x86_64 for old simulators)
  • quiet: Reduce build output verbosity

Interpreting Build Results

Success Response

{
  "success": true,
  "summary": "Build succeeded",
  "warnings": 3,
  "build_time": "45.2s",
  "scheme": "MyApp",
  "configuration": "Debug"
}

Failure Response

{
  "success": false,
  "error": "Build failed",
  "errors": 2,
  "warnings": 5,
  "failure_reason": "Compilation errors in ViewController.swift"
}

Progressive Disclosure

Large build logs use progressive disclosure:

{
  "success": true,
  "summary": "Build succeeded with 15 warnings",
  "cache_id": "build-abc123",
  "quick_stats": {
    "warnings": 15,
    "build_time": "62.3s"
  },
  "next_steps": [
    "Use cache_id to get full build log if needed",
    "Review warnings for potential issues"
  ]
}

Common Build Errors

Error: "No scheme named 'X' found"

Cause: Scheme doesn't exist or isn't shared

Solution:

  1. Run list operation to see available schemes
  2. Check if scheme is shared (Xcode → Product → Scheme → Manage Schemes)

Error: "Code signing identity not found"

Cause: Missing or invalid signing certificate

Solution:

  1. Check Team ID in project settings
  2. Verify certificates in Keychain
  3. Use automatic signing if possible
{
  "operation": "build",
  "scheme": "MyApp",
  "options": {
    "code_sign_identity": "Apple Development",
    "development_team": "TEAM_ID_HERE"
  }
}

Error: "SDK not found"

Cause: Requesting unavailable SDK version

Solution:

  1. Run version operation to see available SDKs
  2. Update sdk option or remove to use latest

Error: "Destination not found"

Cause: Invalid destination specifier

Solution:

  1. Use execute_simulator_command with operation "list" to see available devices
  2. Check device name spelling
  3. Ensure device/simulator is available

Testing Workflows

Complete Test Suite

1. list → Get test scheme
2. clean → Ensure fresh state
3. test → Run all tests
4. Analyze results → Check for failures

Flaky Test Detection

Run tests multiple times:

{
  "operation": "test",
  "scheme": "MyApp",
  "options": {
    "test_iterations": 5,
    "retry_on_failure": true
  }
}

Note: Test iteration support depends on Xcode version.

Test Result Analysis

Tests return:

{
  "success": false,
  "tests_run": 45,
  "tests_passed": 43,
  "tests_failed": 2,
  "failures": [
    {
      "test": "MyAppTests.LoginTests.testInvalidPassword",
      "message": "XCTAssertEqual failed: (\"error\") is not equal to (\"invalid\")"
    }
  ]
}

Project Auto-Detection

xcodebuild operations auto-detect project files:

  1. Searches current directory for .xcworkspace
  2. Falls back to .xcodeproj
  3. Returns error if multiple or none found

Explicit Path:

{
  "operation": "build",
  "project_path": "/path/to/specific/Project.xcodeproj",
  "scheme": "MyApp"
}

Build Performance Tips

1. Enable Parallel Builds

{
  "options": {
    "parallel": true
  }
}

2. Incremental Builds

Don't clean unless necessary - incremental builds are much faster.

3. Reduce Verbosity

For CI/automated builds:

{
  "options": {
    "quiet": true
  }
}

4. Use Derived Data Caching

Default behavior - xcodebuild uses DerivedData for caching.

CI/CD Integration

GitHub Actions Pattern

1. version → Verify Xcode installation
2. list → Validate scheme exists
3. clean → Ensure fresh build
4. build → Compile project
5. test → Run test suite
6. Analyze results → Fail pipeline if tests fail

Build Artifacts

Build produces:

  • .app bundle in DerivedData
  • .xcresult test results bundle
  • Build logs (via progressive disclosure)

Advanced: Build Settings

Query build settings:

{
  "operation": "list",
  "project_path": "/path/to/Project.xcodeproj"
}

Returns scheme/target info. For detailed build settings, use Resource:

xc://reference/build-settings

Scheme Management

Shared vs User Schemes

Shared Schemes:

  • Checked into source control
  • Available to all users
  • Recommended for team projects

User Schemes:

  • Local to your machine
  • Not visible to xcodebuild by default

Best Practice: Share schemes used for CI/CD.

Integration with MCP Tools

This Skill works with execute_xcode_command tool:

  • All operations use the execute_xcode_command tool
  • Tool handles xcodebuild execution and output parsing
  • Tool provides progressive disclosure for large outputs
  • This Skill teaches WHEN and HOW to use operations

Related Skills

  • ios-testing-patterns: Advanced test strategies and analysis
  • simulator-workflows: Device management for testing
  • crash-debugging: Analyzing build crashes

Related Resources

  • xc://operations/xcode: Complete xcodebuild operations reference
  • xc://reference/build-settings: Build settings dictionary
  • xc://reference/error-codes: Common error codes and solutions

Tip: Use list to discover, build to compile, test to validate. Clean only when needed.

Sponsors

Details

Marketplace
conorluddy/xclaude-plugin
Author
Conor Luddy
Category
Community
Keywords
xcode, ios, simulator, testing, idb, accessibility, automation