Loading from mainBundle

2020-03-31 05:02发布

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?

标签: ios swift
1条回答
够拽才男人
2楼-- · 2020-03-31 05:26

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.

查看更多
登录 后发表回答