Appkit

From j4flmao/agent-skills · View interactive version

Appkit is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about AppKit, Cocoa, NSWindow, NSViewController, NSDocument, menus and the responder chain, Objective-C or Swift macOS apps, sandboxing or notarization. Produces native macOS app architecture with AppKit. Not for SwiftUI-first Mac apps (use desktop-swiftui) or cross-platform d

How to use this skill

Skill file

AppKit

Purpose

Build native macOS applications using AppKit — Apple's mature, Objective-C-originated UI framework. AppKit provides deep OS integration, native look and feel, and access to macOS-specific features (menus, toolbars, sheets, drawers, NSTableView, NSCollectionView, document architecture) that SwiftUI cannot fully replace.

Agent Protocol

Trigger

Exact user phrases: "AppKit", "macOS app", "Cocoa framework", "NSView", "NSViewController", "NSTableView", "NSDocument", "native Mac app", "Mac Catalyst", "Objective-C Mac", "Swift AppKit".

Input Context

Output Artifact

AppKit architecture plan with view controller hierarchy, window management, delegation patterns, and data flow design.

Response Format

Architecture: {MVC|MVVM} with {NSViewController tree}
Windows/menus: {NSWindowController, menu items -> actions}
Components: {NSTableView/NSOutlineView/NSCollectionView usage}
Distribution: {App Store sandbox | Developer ID + notarization}
Code: {Swift files}

Completion Criteria

Max Response Length

250 lines.

Framework/Methodology

AppKit Architecture Decision Tree

What type of macOS app?
├── Document-based (files are the primary data unit)
│   → NSDocument + NSDocumentController architecture
│   → Auto-save, versions, NSFileWrapper, UTType declaration
├── Single-window utility (calculator, preferences, toolbar)
│   → NSWindowController + single NSViewController
│   → NSWindow level behavior (floating, modal panel)
├── Multi-window browser/inspector (Xcode, Finder-like)
│   → NSWindowController per window, NSWindowController + delegate
│   → NSWindow restoration, tabs (NSWindowTabGroup)
└── Menu bar app (status item, background process)
    → NSStatusItem + NSMenu (no dock icon if LSUIElement)
    → NSApplication delegate, activateIgnoringOtherApps

MVC in AppKit (Traditional Cocoa Pattern)

Model (NSManagedObject / Codable structs)
    ↕ Bindings or KVO
Controller (NSViewController / NSWindowController)
    ↕ Outlets and Actions
View (NSView subclasses: NSTableView, NSButton, NSTextField)

View Controller Lifecycle

loadView()              // Create view hierarchy programmatically (or load from nib)
  ↓
viewDidLoad()           // Setup initial state, register observers, configure views
  ↓
viewWillAppear()        // View about to appear (update from model)
  ↓
viewDidAppear()         // View appeared (start animations, set first responder)
  ↓
viewWillDisappear()     // View about to disappear (save state)
  ↓
viewDidDisappear()      // View disappeared (stop timers, remove observers)

Workflow

Step 1: Choose Architecture Pattern

| Pattern | Description | Best For |

|---------|-------------|----------|

| MVC (Traditional) | Model-View-Controller, Cocoa native | Simple apps, document-based apps |

| MVVM + Bindings | NSObjectController, ArrayController, bindings in IB | Form-heavy, preferences, inspector panels |

| Presenter | NSViewController as presenter, passive views | Testable logic, moderate complexity |

| Coordinator | AppKit + child view controller coordination | Multi-screen flows, wizards |

| Combine + AppKit | Reactive pipelines with NSObject subscriptions | Modern Swift, async data handling |

Modern approach: Use Combine for binding-like data flow without IB bindings, which are fragile and hard to debug.

class DocumentViewController: NSViewController {
    let viewModel = DocumentViewModel()
    private var cancellables = Set<AnyCancellable>()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.$documentTitle
            .sink { [weak self] title in
                self?.titleLabel.stringValue = title
            }
            .store(in: &cancellables)

        viewModel.$isDirty
            .sink { [weak self] dirty in
                self?.view.window?.isDocumentEdited = dirty
            }
            .store(in: &cancellables)
    }
}

Step 2: Set Up Window and Menu Architecture

// AppDelegate with programmatic window creation
class AppDelegate: NSObject, NSApplicationDelegate {
    var window: NSWindow!

    func applicationDidFinishLaunching(_ notification: Notification) {
        let windowSize = NSSize(width: 1000, height: 700)
        let screenFrame = NSScreen.main?.visibleFrame ?? NSRect.zero
        let windowOrigin = NSPoint(
            x: (screenFrame.width - windowSize.width) / 2,
            y: (screenFrame.height - windowSize.height) / 2
        )

        window = NSWindow(
            contentRect: NSRect(origin: windowOrigin, size: windowSize),
            styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
            backing: .buffered,
            defer: false
        )
        window.title = "My App"
        window.contentViewController = MainSplitViewController()
        window.makeKeyAndOrderFront(nil)
    }

    func applicationWillTerminate(_ notification: Notification) {
        // Save state, close resources
    }
}

Menu System:

// Validating menu items dynamically
override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
    switch menuItem.action {
    case #selector(deleteSelectedItem):
        return tableView.selectedRow >= 0
    case #selector(exportDocument):
        return document != nil
    default:
        return super.validateMenuItem(menuItem)
    }
}

Step 3: Implement Core UI Components

NSTableView (Virtualized List):

class MyTableViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
    @IBOutlet weak var tableView: NSTableView!
    var items: [Item] = []

    // NSTableViewDataSource
    func numberOfRows(in tableView: NSTableView) -> Int { items.count }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        let cell = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView
        cell.textField?.stringValue = items[row].name
        return cell
    }

    // NSTableViewDelegate
    func tableViewSelectionDidChange(_ notification: Notification) {
        let selectedRow = tableView.selectedRow
        // Update detail view
    }
}

Performance Tips for Large NSTableView:

NSCollectionView (Grid/Layout):

let layout = NSCollectionViewFlowLayout()
layout.itemSize = NSSize(width: 200, height: 150)
layout.minimumInteritemSpacing = 16
layout.minimumLineSpacing = 16
layout.sectionInset = NSEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)

let collectionView = NSCollectionView()
collectionView.collectionViewLayout = layout
collectionView.register(MyCollectionViewItem.self, forItemWithIdentifier: .myItem)

Step 4: Implement Drag and Drop

// Pasteboard data types
extension NSPasteboard.PasteboardType {
    static let myCustomType = NSPasteboard.PasteboardType("com.example.myapp.mytype")
}

// Drag source
override func mouseDragged(with event: NSEvent) {
    let pasteboardItem = NSPasteboardItem()
    pasteboardItem.setString(serializedData, forType: .myCustomType)

    let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
    draggingItem.setDraggingFrame(dragImageRect, contents: dragImage)
    beginDraggingSession(with: [draggingItem], event: event, source: self)
}

// Drop destination
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
    return sender.draggingPasteboard.canReadObject(forClasses: [NSString.self], options: nil) ? .copy : []
}

override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
    guard let strings = sender.draggingPasteboard.readObjects(forClasses: [NSString.self], options: nil) as? [String] else { return false }
    handleDroppedStrings(strings)
    return true
}

Step 5: Implement Dark Mode and Accessibility

Dark Mode support is automatic if you use NSColor system colors:

// System colors that adapt automatically
view.layer?.backgroundColor = NSColor.controlBackgroundColor.cgColor
textField.textColor = NSColor.labelColor
placeholderField.textColor = NSColor.secondaryLabelColor

// Custom adaptative colors
let dynamicColor = NSColor(name: "customAccent") { appearance in
    let isDark = appearance.name == .darkAqua || appearance.name == .vibrantDark
    return isDark ? NSColor(red: 0.4, green: 0.6, blue: 1.0, alpha: 1.0) : NSColor(red: 0.0, green: 0.3, blue: 0.8, alpha: 1.0)
}

Accessibility:

// Every NSView subclass must be an NSAccessibilityElement
override func isAccessibilityElement() -> Bool { true }

override func accessibilityRole() -> NSAccessibility.Role { .button }

override func accessibilityLabel() -> String? { "Save document" }

override func accessibilityPerformPress() -> Bool {
    performClick()
    return true
}

Step 6: Sandboxing and Distribution

<!-- Entitlements for sandboxed apps -->
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.files.bookmarks.app-scope</key>
<true/>

Architecture Patterns

Split View Controller (NSSplitViewController)

class MainSplitViewController: NSSplitViewController {
    override func viewDidLoad() {
        let sidebarVC = SidebarViewController()
        let contentVC = ContentViewController()

        let sidebarItem = NSSplitViewItem(sidebarWithViewController: sidebarVC)
        sidebarItem.minimumThickness = 180
        sidebarItem.maximumThickness = 300

        let contentItem = NSSplitViewItem(viewController: contentVC)
        contentItem.minimumThickness = 400

        addSplitViewItem(sidebarItem)
        addSplitViewItem(contentItem)
    }
}

Document-Based App Architecture

class MyDocument: NSDocument {
    @objc dynamic var content = MyDocumentData()

    override class var autosavesInPlace: Bool { true }

    override func makeWindowControllers() {
        let storyboard = NSStoryboard(name: "Main", bundle: nil)
        let wc = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
        addWindowController(wc)

        // Pass data to view controller
        (wc.contentViewController as? DocumentViewController)?.document = self
    }

    override func data(ofType typeName: String) throws -> Data {
        return try JSONEncoder().encode(content)
    }

    override func read(from data: Data, ofType typeName: String) throws {
        content = try JSONDecoder().decode(MyDocumentData.self, from: data)
    }
}

Responder Chain and Target/Action Pattern

The responder chain enables flexible event handling:

  1. First responder (key view → view controller → window → window controller → app delegate)
  2. Cut/copy/paste/selectAll are handled via responder chain
  3. Implement @IBAction methods on any responder for automatic menu validation

Common Pitfalls

| Pitfall | Description | Prevention |

|---------|-------------|------------|

| Retain cycles with delegates | Strong reference from view to delegate | Always use weak references for delegates and dataSources |

| Stale bindings | IB bindings break silently when model changes | Use Combine or willSet/didSet observers instead |

| Main thread blocking | Heavy computation on main thread freezes UI | Dispatch to global queue, update UI on main |

| Improper view lifecycle | Crash when accessing outlets before loadView() | Only access outlets after viewDidLoad() |

| Dark mode breakage | Hardcoded colors look wrong in dark mode | Use NSColor.systemColors or dynamic NSColor always |

| Sandbox denial | App rejected for missing entitlement | Test with sandbox enabled from day one |

| Missing menu validation | Menu items enabled when they shouldn't be | Always implement validateMenuItem: |

| Window state loss | Window position/size not restored | Implement window autosave name, encode restorable state |

| Sheet on wrong window | Sheet on modal panel instead of key window | Call beginSheet: on the correct window |

Best Practices

| Practice | Rationale |

|----------|-----------|

| Use storyboard for menu + windows, programmatic for complex views | Maintains clarity without fighting IB limitations |

| Prefer NSViewController containment over custom container | Built-in child management, responder chain support |

| Use Cocoa Bindings sparingly | Works in IB but breaks silently — replace with Combine |

| Always implement validateMenuItem: | Correct menu state is expected macOS behavior |

| Use NSView's wantsLayer = true for complex rendering | Hardware-accelerated compositing |

| Test with VoiceOver enabled | Accessibility is a requirement, not a feature |

| Use autosave for window state | Users expect restored window positions |

| Prefer Swift over Objective-C for new code | Memory safety, Swift concurrency, Combine |

| Use structured concurrency (async/await) | Avoids callback pyramids, integrates with AppKit |

| Version your Core Data model | Irreversible migration is a support nightmare |

Patterns

Sidebar + Content + Detail (Three-Column Layout)

let sidebar = NSSplitViewItem(sidebarWithViewController: sidebarVC)
let content = NSSplitViewItem(viewController: contentVC)
let detail = NSSplitViewItem(viewController: detailVC)
// Content gets more space: hold splitter position with NSSplitViewItem behavior

Sheet for Modal Tasks

let sheetVC = SheetViewController()
presentAsSheet(sheetVC)
// Or for critical operations:
presentAsModalWindow(sheetVC)

Popover for Transient Information

let popoverVC = PopoverContentViewController()
let popover = NSPopover()
popover.contentViewController = popoverVC
popover.behavior = .transient  // Dismisses on click outside
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .maxY)

Preferences Window

// Use NSTabView in a separate window controller
// NSWindowController with window level .normal (not modal)
// Register defaults via UserDefaults.standard.register(defaults:)

References

Handoff

Hand off to desktop-swiftui for SwiftUI migration strategy. Hand off to design-accessibility for VoiceOver compliance testing.

Architecture Decision Trees

AppKit vs SwiftUI

| Decision | AppKit | SwiftUI |

|---|---|---|

| Minimum OS | macOS 10.0+ | macOS 11.0+ |

| Flexibility | Full control, any UI | Limited to SwiftUI capabilities |

| Performance | Native AppKit views | SwiftUI rendering overhead |

| Interop | — | NSHostingView for embedding |

| Development speed | Slower (manual layout) | Faster (declarative) |

| Future-proof | Stable (legacy) | Apple's focus |

| Best for | Complex, legacy macOS apps | New development, simple UIs |

Storyboard vs Programmatic Layout

| Aspect | Storyboard (XIB) | Programmatic |

|---|---|---|

| Visualization | Visual editor | Runtime only |

| Merge conflicts | Frequent (XML) | Rare (code) |

| Reusability | NIB loading | Custom NSView subclasses |

| Debugging | Hard (runtime connections) | Easy (breakpoints) |

| Team preference | Design-oriented | Code-oriented |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.