Getting the Current NSBundle
- Use
backtrace()to find the function pointer of the caller;- Use
dladdr()to find the executable image path containing this function;- Find the loaded bundle with this executable path.
[…]
With this, I can finally write
Bundle.currenteverywhere, instead ofBundle.mainorBundle(for: AnyClass).
Update (2018-03-12): Leo Natan:
Very cool, but this is an error prone approach due to inlining and optimizations.
For performance,
__builtin_frame_address()/__builtin_return_address()either directly in Swift if possible or in a C shim function would work quite well. Same risks as original approach.