在一些流行的开源swift项目中。我注意到以下方法用于从主bundle加载文件。
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也可以使用这种方法。
We can also use this approach.
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")为什么有人会选择第一种方式超过第二种?
Why would someone choose first approach over second one?
推荐答案这将返回包含 TestClass 类的包:
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.
例如,CocoaPods中的所有Swift库都使用动态框架进行集成,它们部署在主包内的不同包中。所以所有框架都必须使用嵌入式包来访问他们的资源。
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.
我建议使用第一种方法( NSBundle(forClass :)) / code>方法)以提高代码的可移植性。在创建动态框架时需要它。
I'd recommend using the first approach (NSBundle(forClass:) method) to improve code portability. And it's required when creating dynamic frameworks.
更多推荐
从mainBundle加载
发布评论