从mainBundle加载 [英] Loading from mainBundle

查看:91
本文介绍了从mainBundle加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些流行的开源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加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆