In a some popular open source swift project. I noticed following approach used to load a file from main bundle.
@objc class TestClass: NSObject { }
let bundle = NSBundle(forClass: TestClass.self)
let path = bundle.pathForResource(filename, ofType: "json")
We can also use this approach.
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")
Why would someone choose first approach over second one?
This returns the bundle that contains the
TestClass
class:While this returns the main bundle of the application:
If you execute this code from your application code, it will always return your main bundle. But if that class is contained in a different library or framework, it will return the bundle that contains it.
For example, all Swift libraries in CocoaPods are integrated using dynamic frameworks, and they are deployed in a different bundle inside the main bundle. So all the frameworks must use the embedded bundle to access their resources.
I'd recommend using the first approach (
NSBundle(forClass:)
method) to improve code portability. And it's required when creating dynamic frameworks.