ios - 从 mainBundle 加载

标签 ios swift

在一些流行的开源 swift 项目中。我注意到以下方法用于从主包加载文件。

@objc class TestClass: NSObject { }

let bundle = NSBundle(forClass: TestClass.self)
let path = bundle.pathForResource(filename, ofType: "json")

我们也可以使用这种方法。

let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json")

为什么有人会选择第一种方法而不是第二种方法?

最佳答案

这将返回包含 TestClass 类的包:

NSBundle(forClass: TestClass.self)

虽然这会返回应用程序的主要包:

NSBundle.mainBundle()

如果您从您的应用程序代码中执行此代码,它将始终返回您的主包。但如果该类包含在不同的库或框架中,它将返回包含它的包。

例如,CocoaPods 中的所有 Swift 库都是使用动态框架集成的,并且它们部署在主包内的不同包中。所以所有的框架都必须使用嵌入式包来访问它们的资源。

我建议使用第一种方法(NSBundle(forClass:) 方法)来提高代码的可移植性。创建动态框架时需要它。

关于ios - 从 mainBundle 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36474106/

相关文章:

iphone - 如何解决表格 View 中的滚动问题

ios - 导航栏中的标题文本不会立即截断

ios - Nib 必须恰好包含一个顶级对象,该对象必须是 UITableViewCell 实例。在其他 UITableViews 中工作

ios - 在快速的委托(delegate)数组中查找委托(delegate)

ios - Playground 执行失败 : <EXPR>:15:33: error: type 'Int' does not conform to protocol 'BooleanType'

swift - 在另一个新框架中添加 2 个框架

ios - Swift 延迟函数似乎不适用于 textField 委托(delegate) shouldChangeCharactersIn

iphone - 将数据从 NSObject 发送到 UIViewController

ios - Realm 迁移 : Why in documentation it is recommended to call the migration block each time without checking the schema version before?

ios - 忽略文件,文件 .../Social.framework/Social(3 片)中缺少所需的架构 x86_64