Category method collision causes unpredictable selector resolution at runtime
0 reputation · 18 Aug 2022, 04:30 UTC
Unpredictable category method resolution
When multiple categories on the same class implement an identical selector, the Objective-C runtime resolves the method at load time based on binary load order. This order is not guaranteed to be consistent across architectures, linker versions, or even successive launches. The Apple documentation explicitly labels this behavior as undefined, yet no compiler diagnostic warns about cross-module collisions — -Wobjc-category-redefinition only catches duplicate categories within a single translation unit.
The goal is to achieve deterministic method resolution for a selector added via categories, without relying on fragile load-order assumptions. Constraints include: third-party libraries cannot be modified to prefix their category methods, the class in question is a system type (e.g., NSString) that cannot be subclassed for this purpose, and method swizzling introduces its own ordering dependencies when multiple parties swizzle the same selector.
Questions
- Is there a linker or runtime mechanism to enforce a specific category implementation priority without modifying the categories themselves?
- Can a build-time check be implemented to detect cross-module selector collisions before they manifest as runtime nondeterminism?
- Does the modern objc4 runtime provide any introspection API to query which category supplied a resolved method implementation at runtime?