Sample CodeiOS, iPadOS, Mac Catalyst, macOS, tvOSReviewed 2026-07-21View on Apple Developer

Creating a custom Metal view

At a glance

Item Summary
Purpose Implement a lightweight view for Metal rendering that’s customized to your app’s needs.
App architecture A C/Objective-C header, Metal, Objective-C sample with the source-visible chain mainAAPLViewControllerAAPLRendererMetal APIs.
Main patterns View-controller organization, Protocol-oriented abstraction, Delegate or data-source callbacks
Project style 18 scanned source file(s) across C/Objective-C header, Metal, Objective-C, organized around ranked entry, type, and file boundaries.
Execution model No structured execution marker indexed; callback threading requires source review.
State/event model No structured observation or publisher-scheduling marker indexed.
Key frameworks/packages Metal, UIKit, QuartzCore, Cocoa, simd; these are source dependencies, not architecture labels.

Project structure

Source bundle/
└── Application/
    ├── main.m
    ├── AAPLAppDelegate.h
    ├── AAPLView.h
    ├── AAPLAppDelegate.m
    ├── AAPLView.m
    ├── AAPLViewController.h
    ├── AAPLViewController.m
    ├── AppKit/
    │   ├── AAPLNSView.h
    │   └── AAPLNSView.m
    ├── UIKit/
    │   ├── AAPLUIView.h
    │   └── AAPLUIView.m
    └── WindowSceneDelegate.h

Structure observations

  • Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
  • Primary languages: C/Objective-C header, Metal, Objective-C.
  • The verified tree contains 9 project/configuration file(s) and 9 source declaration(s).

Overall architecture

Reference code

Application/main.m:18 — architecture anchor

#if defined(TARGET_IOS) || defined(TARGET_TVOS)
int main(int argc, char * argv[]) {

    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AAPLAppDelegate class]));
    }
}
#endif

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into Metal.

Ownership and state

Ownership evidence

Application/AAPLView.h:34 — stored dependency or nearest verified ownership anchor

@interface AAPLView : NSView <CALayerDelegate>
// ...
@property (nonatomic, nonnull, readonly) CAMetalLayer *metalLayer;
// ...
@end
Owner Object or state Relationship Mutation authority
AAPLView CAMetalLayer (metalLayer) stores or receives The declaring implementation writes; property clients read
AAPLView BOOL (paused) stores or receives Header-visible collaborators
AAPLView id (delegate) stores or receives Header-visible collaborators
WindowSceneDelegate UIWindow (window) retains or copies an assigned value Header-visible collaborators

Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

No source-visible execution, scheduling, or synchronization boundary was found in the indexed source.

@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Source import Metal The cited file imports this module; runtime use and architectural role are not inferred. Application/AAPLView.h:9
Source import UIKit The cited file imports this module; runtime use and architectural role are not inferred. Application/AAPLAppDelegate.h:9
Source import QuartzCore The cited file imports this module; runtime use and architectural role are not inferred. Application/AAPLView.h:8
Source import Cocoa The cited file imports this module; runtime use and architectural role are not inferred. Application/AAPLAppDelegate.h:11
Source import simd The cited file imports this module; runtime use and architectural role are not inferred. Renderer/AAPLShaderTypes.h:11
Source import AppKit The cited file imports this module; runtime use and architectural role are not inferred. Application/AppKit/AAPLNSView.h:9

receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.

Class and protocol design

Application/AAPLView.h:19 — representative type boundary

@protocol AAPLViewDelegate <NSObject>

- (void)drawableResize:(CGSize)size;

- (void)renderToMetalLayer:(nonnull CAMetalLayer *)metalLayer;

@end
Type Responsibility Depends on or conforms to
AAPLViewDelegate Defines a capability or collaboration contract NSObject
AAPLAppDelegate Receives callback-driven events UIResponder, UIApplicationDelegate
AAPLView User-interface presentation and input forwarding UIView, CALayerDelegate
AAPLViewController View lifecycle, callbacks, and feature coordination PlatformViewController, AAPLViewDelegate
AAPLNSView User-interface presentation and input forwarding AAPLView
AAPLUIView User-interface presentation and input forwarding AAPLView
WindowSceneDelegate Receives callback-driven events UIResponder, UIWindowSceneDelegate
AAPLRenderer Owns drawing, GPU, or presentation processing NSObject
RasterizerData Represents feature data Concrete collaborators/imported frameworks

The source explicitly defines local protocol relationships: AAPLViewControllerAAPLViewDelegate.

Access control

Symbol Access Verified effect Likely rationale
metalLayer (Application/AAPLView.h:34) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
paused (Application/AAPLView.h:36) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
delegate (Application/AAPLView.h:38) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
window (Application/WindowSceneDelegate.h:13) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.

Reference code

Application/AAPLView.h:34 — representative boundary

@interface AAPLView : NSView <CALayerDelegate>
// ...
@property (nonatomic, nonnull, readonly) CAMetalLayer *metalLayer;
// ...
@end

Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.

Logic ownership and placement

Logic Owning type or file Placement rationale
View lifecycle, callbacks, and feature coordination AAPLViewController The source’s Controller suffix makes this role explicit.
Receives callback-driven events AAPLAppDelegate, AAPLViewDelegate, WindowSceneDelegate The source’s Delegate suffix makes this role explicit.
Owns drawing, GPU, or presentation processing AAPLRenderer The source’s Renderer suffix makes this role explicit.
User-interface presentation and input forwarding AAPLNSView, AAPLUIView, AAPLView The source’s View suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization Application/AAPLViewController.h:18 A controller is the verified coordination boundary; this is MVC-style only where a separate model is present.
Protocol-oriented abstraction Application/AAPLViewController.h:18 A local protocol and concrete conformance create an explicit capability boundary.
Delegate or data-source callbacks Application/AAPLAppDelegate.h:15 Callback protocols invert event delivery back into the sample’s owner.

Main application flow

Reference code

Renderer/AAPLRenderer.m:172renderToMetalLayer()

- (void)renderToMetalLayer:(nonnull CAMetalLayer*)metalLayer
{
    // ...
    _frameNum++;
    id <MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
    id<CAMetalDrawable> currentDrawable = [metalLayer nextDrawable];
    if(!currentDrawable)
    {
        return;
    }
    _drawableRenderDescriptor.colorAttachments[0].texture = currentDrawable.texture;
    id <MTLRenderCommandEncoder> renderEncoder =
        [commandBuffer renderCommandEncoderWithDescriptor:_drawableRenderDescriptor];
    [renderEncoder setRenderPipelineState:_pipelineState];
    [renderEncoder setVertexBuffer:_vertices
                            offset:0
                           atIndex:AAPLVertexInputIndexVertices ];
    {
        AAPLUniforms uniforms;
#if ANIMATION_RENDERING
        uniforms.scale = 0.5 + (1.0 + 0.5 * sin(_frameNum * 0.1));
#else
        uniforms.scale = 1.0;
#endif
        uniforms.viewportSize = _viewportSize;
        [renderEncoder setVertexBytes:&uniforms
                               length:sizeof(uniforms)
                              atIndex:AAPLVertexInputIndexUniforms ];
    }
    [renderEncoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:6];
    [renderEncoder endEncoding];
    [commandBuffer presentDrawable:currentDrawable];
    [commandBuffer commit];
}

Naming conventions

  • Types: Controller: AAPLViewController; Delegate: AAPLAppDelegate, AAPLViewDelegate, WindowSceneDelegate; Renderer: AAPLRenderer; View: AAPLNSView, AAPLUIView, AAPLView.
  • Protocols: AAPLViewDelegate.
  • Methods: drawableResize, renderToMetalLayer, initCommon, resizeDrawable, stopRenderLoop, render, application, applicationShouldTerminateAfterLastWindowClosed.
  • Files: Application/AAPLAppDelegate.h, Application/AAPLView.h, Application/AAPLAppDelegate.m, Application/AAPLView.m, Application/AAPLViewController.h, Application/AAPLViewController.m.

Architecture takeaways

  • main is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches Metal, UIKit, QuartzCore, Cocoa through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
  • Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
  • Access-control conclusions separate verified language visibility from the likely design rationale.
  • Local protocol relationships provide an explicit substitution boundary.

Source map

Source file Relevant symbols
Application/main.m Cited implementation, Feature implementation
Application/AAPLView.h Cited implementation, AAPLViewDelegate, metalLayer, paused, delegate, Metal, QuartzCore, AAPLView
Application/WindowSceneDelegate.h window, WindowSceneDelegate
Application/AAPLViewController.h AAPLViewController, Cited implementation
Application/AAPLAppDelegate.h Cited implementation, UIKit, Cocoa, AAPLAppDelegate
Renderer/AAPLShaderTypes.h simd, Feature implementation
Application/AppKit/AAPLNSView.h AppKit, AAPLNSView
Application/AAPLAppDelegate.m AAPLAppDelegate
Application/AAPLView.m AAPLView
Application/AAPLViewController.m AAPLViewController
Application/AppKit/AAPLNSView.m AAPLNSView
Application/UIKit/AAPLUIView.h AAPLUIView
Application/UIKit/AAPLUIView.m AAPLUIView
Application/WindowSceneDelegate.m WindowSceneDelegate
Renderer/AAPLRenderer.h AAPLRenderer
Renderer/AAPLRenderer.m AAPLRenderer