
xclaude-plugin
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-marketplaceRun it inside Claude Code after adding the marketplace with /plugin marketplace add conorluddy/xclaude-plugin.
Contents
Discovered from sourceSkills 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:
- Validating accessibility compliance before release
- Debugging VoiceOver issues or user reports
- Implementing new features that need accessibility support
- Running accessibility audits as part of CI/CD
- Testing Dynamic Type support and contrast ratios
- Verifying semantic markup and element roles
- 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
| Task | Tool/Operation | Typical Time |
|---|---|---|
| Check accessibility quality | accessibility-quality-check | ~80ms |
| Query full accessibility tree | idb-ui-describe | ~120ms |
| Find element by label | idb-ui-find-element | ~100ms |
| Screenshot (fallback only) | screenshot | ~2000ms |
| VoiceOver simulation | Manual 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:
-
accessibilityLabel: What element is
- Example: "Profile photo", "Send message button"
- Should be concise, descriptive
-
accessibilityValue: Current state/value
- Example: "50%", "Selected", "3 of 10"
-
accessibilityHint: What happens when activated
- Example: "Opens your profile settings"
- Use sparingly, only when action isn't obvious
-
accessibilityTraits: Element behavior
- Button, Link, Header, Selected, etc.
-
isAccessibilityElement: Should be exposed
truefor interactive/informative elementsfalsefor 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:
- Query accessibility tree
- Check elements appear in logical order
- No gaps in navigation
- 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
describedoesn't show it - VoiceOver skips element
Solutions:
- Check
isAccessibilityElement = true - Verify not hidden:
isHidden = false - Check not covered by another element
- Ensure frame is not CGRect.zero
- Verify
accessibilityElementsHidden = falseon parents
Problem: Wrong Reading Order
Symptoms:
- Elements announced in illogical order
- Navigation jumps around screen
Solutions:
- Check view hierarchy (Z-order affects reading order)
- Use
accessibilityElementsarray to set explicit order:containerView.accessibilityElements = [label, field, button] - Group related elements in accessibility containers
Problem: Insufficient Context
Symptoms:
- Labels too generic: "button", "image", "item"
- Users can't identify purpose
Solutions:
- Add specific context to label
- Include state information in value
- Use hint for non-obvious actions
- 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 referencexc://reference/wcag: WCAG 2.1 guidelines mapped to iOSxc://workflows/accessibility-first: This workflow patternxc://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
| Task | Tool/Command | Location |
|---|---|---|
| View crash logs | Console.app | macOS Application |
| Retrieve simulator crashes | ~/Library/Logs/DiagnosticReports/ | File system |
| Symbolicate crash | atos | Command line |
| Find dSYM files | Xcode Organizer / DerivedData | Xcode |
| Analyze crash type | Stack trace patterns | Crash 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:
- dSYM file matching the build UUID
- Binary (MyApp.app/MyApp)
- 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 Type | Meaning | Common Cause |
|---|---|---|
| EXC_BAD_ACCESS | Invalid memory access | Dangling pointer, use-after-free |
| SIGABRT | Process aborted | Assertion failure, force unwrap nil |
| EXC_BREAKPOINT | Breakpoint hit | Swift runtime error, fatal error |
| SIGILL | Illegal instruction | Corrupted code, wrong architecture |
| SIGSEGV | Segmentation fault | Memory corruption |
| SIGBUS | Bus error | Unaligned 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:
- dSYM is in Spotlight index
- 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:
- Xcode → Window → Organizer
- Select "Crashes" tab
- Drag crash log into window
- 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
- Open file at crash location (ViewController.swift:45)
- Examine function
loginButtonTapped() - Check for:
- Optional unwrapping (
!or?) - Array/dictionary access
- Object references
- Memory management
- Optional unwrapping (
Step 4: Reproduce Locally
- Set breakpoint at crash location
- Follow stack trace path
- Inspect variables and state
- Identify null/invalid values
Step 5: Validate Fix
- Apply fix
- Build and test
- Verify no regression
- 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
weakvsunsafe_unretainedreferences - 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
applicationDidEnterBackgroundquickly - 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:
- 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
- Match UUID
Compare dSYM UUID with crash log Binary Images UUID. They must match exactly.
- Archive dSYMs
Enable "Archive" in scheme settings to preserve dSYMs for releases.
- 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:
- Disable Optimizations
Build Settings:
- Optimization Level: None [-O0]
- Debug Information Format: DWARF with dSYM File
- Build with Debug Configuration
{
"operation": "build",
"scheme": "MyApp",
"configuration": "Debug"
}
- 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:
- Check Parameters
Before system call, validate:
- Non-nil objects
- Valid ranges
- Correct types
- Review Constraints
Auto Layout issues often cause UIKit crashes:
- Check constraint conflicts
- Verify view hierarchy
- 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:
- Check Library Version
Ensure compatible version:
- Update to latest stable
- Check release notes for bug fixes
- Review Integration
Verify:
- Correct API usage
- Thread safety
- Initialization order
- 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
- 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:
- Click "Crash Reports" in sidebar
- Enter app name in search
- 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 referencexc://workflows/symbolication: Detailed symbolication guidexc://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
| Task | Operation | Key Parameters |
|---|---|---|
| Run all tests | test | scheme, destination |
| Run specific test | test | scheme, only_testing |
| Skip tests | test | scheme, skip_testing |
| Use test plan | test | scheme, test_plan |
| Parallel execution | test | destination (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:
- Check
successstatus - Review
tests_failedcount - Examine
failuresarray for details - Check
execution_timefor performance issues - 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:
- Timeout failures: "Exceeded timeout of 30 seconds"
- Element not found: "Failed to find button..." (UI tests)
- Race conditions: "Expected 5 but got 4"
- Async timing: "Asynchronous wait failed"
- 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:
- Use
setUp()andtearDown()methods - Clear app state between tests
- Use unique test data per test
- Avoid shared static state
- Reset UserDefaults in setUp
- Clear keychain data
- 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:
- Check crash logs for stack trace
- Run test in debugger (Xcode)
- Add breakpoints at crash location
- 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:
- Increase timeout for element queries
- Wait for animations to complete
- Verify accessibility identifiers
- Scroll element into view
- 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:
- Increase expectation timeout
- Mock network requests
- Check for deadlocks
- Verify expectation fulfillment
- 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:
- Profile memory usage
- Optimize test efficiency
- Break up long-running tests
- Check for memory leaks
- 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:
-
App Launch Timeout: App takes too long to launch
- Solution: Optimize app startup, increase timeout
-
Element Query Timeout: UI element not found
- Solution: Wait for element existence, check identifiers
-
Network Timeout: API requests fail
- Solution: Mock network, increase timeout, fix connectivity
-
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:
- Previous app installation interfering
- Simulator storage full
- Corrupt simulator data
- 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:
- Ensure Test Isolation:
override func setUp() {
super.setUp()
// Reset all shared state
AppState.shared.reset()
clearDatabase()
}
- Avoid Singletons:
// Bad: Shared state
class APIManager {
static let shared = APIManager()
}
// Good: Dependency injection
class APIManager {
// Inject per test
}
- 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 referencexc://reference/xctest: XCTest framework documentationxc://reference/xcuitest: XCUITest framework documentationxc://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:
-
App Performance Issues
- Slow app launch times
- Choppy scrolling or animations
- UI freezing or unresponsiveness
- High CPU usage
-
Memory Problems
- Memory leaks detected
- Growing memory footprint
- Memory warnings
- App crashes due to memory pressure
-
Network Inefficiencies
- Slow data loading
- Excessive network requests
- Large payload sizes
- Poor offline handling
-
Energy Consumption
- Battery drain complaints
- Background processing issues
- Thermal throttling
- Energy impact reports
-
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:
- Open Instruments (Xcode → Open Developer Tool → Instruments)
- Select "Time Profiler" template
- Choose device and app
- Click record, perform problematic operations
- 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:
- Take memory snapshot (Mark Generation)
- Perform operation (e.g., open/close view controller)
- Take another snapshot
- 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:
- Run app in Xcode
- Click "Debug Memory Graph" button
- Filter by leaked objects
- 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:
- Profile App Launch
instruments -t "App Launch" \
-D /path/to/launch.trace \
-w <device-udid> \
com.example.MyApp
- 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
- 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:
- Profile Scrolling
instruments -t "Core Animation" \
-D /path/to/scroll.trace \
-w <device-udid> \
com.example.MyApp
-
Check Frame Rate
- Target: 60 FPS (16.67ms per frame)
- Acceptable: 50-60 FPS
- Poor: < 50 FPS
-
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:
-
Identify Suspect Feature
- Feature that shows memory growth
- Example: Opening/closing profile view
-
Create Reproduction Steps
1. Launch app 2. Open profile view 3. Close profile view 4. Repeat 10 times -
Profile with Leaks
- Use Leaks instrument
- Follow reproduction steps
- Check for leaks after each iteration
-
Analyze Leak Origin
- Click leaked object
- View "Responsible Caller"
- Trace back to source code
-
Identify Leak Pattern
- Closure capture:
[weak self]missing - Delegate: Not marked
weak - Notification: Observer not removed
- Timer: Not invalidated
- Closure capture:
-
Fix and Verify
- Apply fix
- Profile again
- Confirm leak eliminated
Network Request Optimization
Analysis Workflow:
-
Baseline Measurement
- Profile typical user session
- Count total requests
- Measure total bytes transferred
-
Identify Inefficiencies
- Too many requests: Batch or consolidate
- Large payloads: Compress or paginate
- Redundant data: Implement caching
- Sequential requests: Parallelize when possible
-
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:
reloadDatatook 1000ms total- 10ms in
reloadDataitself - 800ms in
configure(called fromreloadData) - 700ms in
processImage(called fromconfigure)
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:
-
Capture Memory Graph
- Run app in Xcode
- Click "Debug Memory Graph" button (or ⌘⌥M)
-
Filter View
- Filter by "Leaks" to see leaked objects
- Filter by class name to find specific objects
-
Inspect Object
- Select object in left panel
- View properties in right panel
- See references in reference inspector
-
Trace Retain Cycle
- Follow strong references
- Identify circular paths
- Note where
weakshould 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:
-
Establish Baseline
- Profile app on reference device
- Record key metrics (launch time, memory, FPS)
- Store baseline measurements
-
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()
}
}
-
CI Integration
- Run performance tests in CI
- Compare results to baseline
- Fail build if regression > threshold
-
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:
- Edit scheme → Run → Build Configuration → Release
- Enable "Debug executable" for debugging symbols
- Build and run
- Profile as normal
Warning: Some crashes only happen in release due to optimizations.
Continuous Performance Monitoring
Development Workflow:
- Baseline establishment: Profile app at start of sprint
- Feature development: Build features normally
- Pre-merge profiling: Profile before merging to main
- Regression check: Compare to baseline
- 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 buildsxc://reference/instruments: Complete Instruments template referencexc://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_commandfor 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 simctlcommands - ❌ NEVER: Use
simctldirectly in bash - ❌ NEVER: Run
xcrun simctlcommands 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 devices | xcrun simctl list | execute_simulator_command op: "list" |
| Boot simulator | xcrun simctl boot <UDID> | execute_simulator_command op: "device-lifecycle" sub: "boot" |
| Install app | xcrun simctl install <UDID> <app.app> | execute_simulator_command op: "app-lifecycle" sub: "install" |
| Launch app | xcrun simctl launch <UDID> <bundle-id> | execute_simulator_command op: "app-lifecycle" sub: "launch" |
| Screenshot | xcrun simctl io <UDID> screenshot | execute_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
| Task | MCP Tool | Operation | Sub-Operation |
|---|---|---|---|
| List devices | execute_simulator_command | list | - |
| Boot device | execute_simulator_command | device-lifecycle | boot |
| Shutdown device | execute_simulator_command | device-lifecycle | shutdown |
| Create device | execute_simulator_command | device-lifecycle | create |
| Delete device | execute_simulator_command | device-lifecycle | delete |
| Install app | execute_simulator_command | app-lifecycle | install |
| Launch app | execute_simulator_command | app-lifecycle | launch |
| Screenshot | execute_simulator_command | io | screenshot |
| Health check | execute_simulator_command | health-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:
- Run
listto see exact device names - Use UDID instead of name
- Check device hasn't been deleted
Unable to Boot
Problem: Boot fails or times out
Solutions:
- Check disk space (simulators need space)
- Shutdown other running simulators
- Restart CoreSimulator:
killall -9 com.apple.CoreSimulator.CoreSimulatorService - Run
health-checkto validate environment
App Install Fails
Problem: Install operation fails
Solutions:
- Verify .app path is correct
- Check device is booted
- Ensure .app is built for simulator (not device)
- Try erasing simulator first
App Won't Launch
Problem: Launch succeeds but app crashes immediately
Solutions:
- Check app logs in Console.app
- Verify app is signed correctly
- Check for missing frameworks/resources
- 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_commandtool - 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 referencexc://reference/device-specs: Available device types and runtimesxc://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:
-
Optimize Token Usage
- Working with large device lists or build logs
- Reducing context window consumption
- Implementing efficient query patterns
-
Manage Cache State
- Understanding when responses are cached
- Invalidating stale cache entries
- Querying cached data efficiently
-
Handle Configuration
- Setting up consistent build environments
- Managing simulator preferences
- Configuring test execution parameters
-
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:
- Summary - Key metrics and booted devices (~100 tokens)
- cache_id - Reference to full dataset
- 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:
listoperations (device lists, app lists)buildoperations (build logs, test results)describeoperations (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):
listoperations (device list changes infrequently)versionoperations (Xcode version is stable)show-build-settings(project config changes rarely)
Moderate Cache Value (Medium TTL):
buildoperations (results valid until code changes)testoperations (results valid until code/tests change)describeoperations (UI state changes moderately)
Low Cache Value (Short TTL):
device-lifecycle(device state changes frequently)app-lifecycle(app state is dynamic)input/tapoperations (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.,
cleaninvalidatesbuildcache)
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_IDENTIFIERDEVELOPMENT_TEAMCODE_SIGN_IDENTITYSDKROOTARCHS
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 endpointFEATURE_FLAGS- Enable/disable featuresTEST_MODE- Testing-specific behaviorLOG_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)listwith large device sets (1-5 seconds)describewith 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: truefor list operations - Request
summaryoutput format for builds - Query cache_id before full details
- Use
quiet: truefor 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 dataxcodebuild-build- Returns cache_id for build logsxcodebuild-test- Returns cache_id for test resultssimctl-list- Returns cache_id for device listsidb-ui-describe- Returns cache_id for UI trees
Cache Management Tools:
xcodebuild-get-details- Query cached build datasimctl-get-details- Query cached simulator datacache- Manage cache configurationpersistence- 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 detailsxc://reference/token-optimization- Token efficiency guidexc://workflows/progressive-disclosure- Pattern documentationxc://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_commandfor 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
idbcommands - ❌ NEVER: Use
idbdirectly in bash - ❌ NEVER: Run
idbcommands 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?
| Approach | Time | Tokens | Reliability |
|---|---|---|---|
| Accessibility tree | ~120ms | ~50 | Survives theme changes |
| Screenshot | ~2000ms | ~170 | Breaks 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 labelstype: Button, TextField, Cell, etc.value: Current input valuevisible: 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:
-
Accessibility quality is "poor"
{ "operation": "check-accessibility", "target": "booted" } -
Visual verification needed
- Checking UI layout
- Verifying colors/images
- Debug visual issues
-
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:
- Query full tree with
describeto see all elements - Check if element is in a scroll view (may be off-screen)
- Verify app state (correct screen?)
- Check if element has accessibility label
Tap Not Working
Problem: Tap executes but nothing happens
Solutions:
- Verify element is
enabled: true - Check element is
visible: true - Confirm coordinates are correct (use
centerX,centerY) - Element might need double-tap or long-press
Input Not Working
Problem: Text input not appearing
Solutions:
- Tap text field first to focus
- Wait for keyboard to appear
- Check field is not disabled
- 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
- Batch Operations: Group describe queries to minimize round-trips
- Cache Tree: Reuse accessibility tree if UI hasn't changed
- Target Specific Areas: Use
describewith point coordinates for specific regions - 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_commandtool - 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 referencexc://reference/accessibility: Accessibility tree structure guidexc://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_commandfor 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
xcodebuildcommands - ❌ NEVER: Use
xcodebuilddirectly in bash - ❌ NEVER: Run
xcrun xcodebuildin 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 schemes | xcodebuild -list | execute_xcode_command op: "list" |
| Build app | xcodebuild -scheme... | execute_xcode_command op: "build" |
| Run tests | xcodebuild -scheme... test | execute_xcode_command op: "test" |
| Clean build | xcodebuild clean | execute_xcode_command op: "clean" |
| Get Xcode info | xcodebuild -version | execute_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
| Task | MCP Tool | Operation | Key Parameters |
|---|---|---|---|
| Build for simulator | execute_xcode_command | build | scheme, configuration:Debug |
| Build for device | execute_xcode_command | build | scheme, configuration:Release, destination |
| Run tests | execute_xcode_command | test | scheme, destination |
| Clean build | execute_xcode_command | clean | scheme |
| List schemes | execute_xcode_command | list | - |
| Get Xcode info | execute_xcode_command | version | - |
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:
- Run
listoperation to see available schemes - Check if scheme is shared (Xcode → Product → Scheme → Manage Schemes)
Error: "Code signing identity not found"
Cause: Missing or invalid signing certificate
Solution:
- Check Team ID in project settings
- Verify certificates in Keychain
- 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:
- Run
versionoperation to see available SDKs - Update
sdkoption or remove to use latest
Error: "Destination not found"
Cause: Invalid destination specifier
Solution:
- Use
execute_simulator_commandwith operation "list" to see available devices - Check device name spelling
- 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:
- Searches current directory for
.xcworkspace - Falls back to
.xcodeproj - 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:
.appbundle in DerivedData.xcresulttest 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_commandtool - 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 referencexc://reference/build-settings: Build settings dictionaryxc://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