Swift Hipster
Swift Hipster

Reputation: 1664

Loading from mainBundle

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?

Upvotes: 1

Views: 429

Answers (1)

redent84
redent84

Reputation: 19239

This returns the bundle that contains the TestClass class:

NSBundle(forClass: TestClass.self)

While this returns the main bundle of the application:

NSBundle.mainBundle()

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.

Upvotes: 3

Related Questions