Loading from mainBundle

前端 未结 1 1571
醉酒成梦
醉酒成梦 2021-01-16 12:27

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 bun         


        
相关标签:
1条回答
  • 2021-01-16 12:39

    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.

    0 讨论(0)
提交回复
热议问题