framwork如何读取bundle资源

一般来说,bundle都会放在跟framwork同一级目录,这样读取、更新起来比较方便

读取bundle路径有两种方式,这两种方式读取出来的

直接使用mainBundle来获取自定义bundle路径

//读取bundle
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"XXX" ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
//获取图片
    NSString *filePath = [bundle pathForResource:@"back@2x" ofType:@"png"]; //这个需要目标图片全名,不然返回nil (获取文件路径)
    UIImage *image = [UIImage imageWithContentsOfFile:filePath];
    UIImage *image1 = [UIImage imageNamed:@"back" inBundle:bundle compatibleWithTraitCollection:nil];//这种方式读取图片不需要@2x后缀,比第一种图片读取方式方便些
//获取其他类型的文件
    NSString *filePath2 = [bundle pathForResource:@"index" ofType:@"hmtl"]; //文件名、文件类型
    NSURL *baseUrl = [NSURL fileURLWithPath:bundlePath isDirectory:YES];
    NSString *indexContent = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
//[self.webView loadHTMLString:indexContent baseURL:baseUrl];//加载网页代码
  • bundleForClass 官方文档的解释 (dynamically 动态的)
  • Return Value
    The NSBundle object that dynamically loaded aClass (a loadable bundle), the NSBundle object for the framework in which aClass is defined, or the main bundle object if aClass was not dynamically loaded or is not defined in a framework.
    This method creates and returns a new NSBundle object if there is no existing bundle associated with aClass. Otherwise, the existing instance is returned.

通俗的理解就是,返回当class所在的bundle,如果不是动态库,就返回主工程的bundle,所以我们一般用起来就跟直接获取mainBundle基本是一样的

    NSString *bundlePath = [[NSBundle bundleForClass:[self class]].resourcePath stringByAppendingPathComponent:@"XXX.bundle"];        
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];                                 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容