tezvyn:

Custom Frameworks: Best Practices for Sharing Code

AI-drafted, machine-checkedSource: developer.apple.comadvanced

A custom framework is a private toolkit, bundling shared code and resources for use across multiple apps. Use them for common logic in an app suite, but always prefix public symbols to avoid name collisions and static link errors.

WHY IT EXISTS To solve the problem of code duplication and maintenance across multiple related applications. Instead of copying and pasting common logic, a framework centralizes it into a single, shareable unit, making updates easier and ensuring consistency.

THE MENTAL MODEL A custom framework is a self-contained, reusable package of code and resources like images, sounds, or UI files. It's a shareable library that multiple applications can use. Think of it as creating your own private version of a system framework like Core Graphics, but for your own suite of apps.

HOW IT WORKS You compile code and bundle resources into a specific directory structure that the system recognizes as a framework. At runtime, an application loads this framework's code into its memory space. While the dynamic linker finds symbols at runtime, the static linker must first resolve them at compile time. This is where naming is critical. You must add a unique prefix to all global symbols (classes, functions, variables) to prevent the static linker from finding duplicate definitions if another framework uses the same name, which would cause a build failure.

WHEN TO USE IT Use a framework when you have code or resources that are shared by multiple applications, like in a suite of products. It's also useful within a single large application to separate generic, reusable components from application-specific logic, simplifying maintenance and improving modularity.

WHEN NOT TO USE IT Avoid creating a framework for code that is only used in one specific application and is not reusable. Frameworks introduce a small amount of overhead for loading and memory usage. If the code isn't shared, the overhead may be unnecessary; packaging it with the main application is more efficient.

ONE CANONICAL EXAMPLE A company building a suite of three apps—a calendar, a to-do list, and a note-taker—could create a custom framework called "CommonKit". This framework would contain shared networking code for their backend service and authentication logic. Each of the three apps would include the "CommonKit" framework. All public functions might be prefixed with "CK", like CKAuthenticateUser(), to avoid conflicts with other libraries.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.