从mainBundle加载

编程入门 行业动态 更新时间:2024-10-24 22:30:47
本文介绍了从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加载

本文发布于:2023-07-16 07:25:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   mainBundle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!