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];                                 

你可能感兴趣的:(framwork如何读取bundle资源)