← Back to Tutorials

16. System Management & Debugging

System Management

Memory Management

ARC automatically manages memory. Avoid retain cycles with weak references:

class Parent {
    var child: Child?
}

class Child {
    weak var parent: Parent?   // weak prevents retain cycle
    var closure: (() -> Void)?
    
    func setup() {
        // [weak self] avoids retain cycle in closures
        closure = { [weak self] in
            guard let self = self else { return }
            print("Child: \(self)")
        }
    }
}

Instruments

Xcode's profiling tool for performance analysis:

Launch Instruments via Product → Profile (Cmd + I) in Xcode.

LLDB Debugging

LLDB commands in Xcode's console:

// Basic commands
po variableName        // Print object description
p variableName         // Print value
expr variable = 10     // Modify variable at runtime
bt                    // Backtrace / call stack
thread info           // Current thread details
breakpoint set --name viewDidLoad  // Set breakpoint

Crash Reporting

Integrate crash reporting services like Firebase Crashlytics:

import FirebaseCrashlytics

// Log custom events
Crashlytics.crashlytics().log("User tapped purchase button")

// Set user info
Crashlytics.crashlytics().setUserID("user123")
Crashlytics.crashlytics().setCustomValue(100, forKey: "score")

// Record a non-fatal error
let error = NSError(domain: "com.example",
    code: 100,
    userInfo: [NSLocalizedDescriptionKey: "Network timeout"])
Crashlytics.crashlytics().record(error: error)

// Force a crash for testing
// Crashlytics.crashlytics().crash()

Testing

Xcode supports Unit Tests, UI Tests, and Performance Tests:

import XCTest

class MyAppTests: XCTestCase {
    let calculator = Calculator()
    
    func testAddition() {
        let result = calculator.add(2, 3)
        XCTAssertEqual(result, 5)
    }
    
    func testPerformance() {
        measure {
            _ = calculator.calculateFibonacci(30)
        }
    }
}
Practice Task: Create a simple "Performance Test" app. Add a button that creates memory-intensive operations. Use Instruments (Allocations and Leaks) to identify any issues. Fix a retain cycle. Write at least 5 unit tests using XCTest. Configure Crashlytics and force a test crash to verify the setup.