• IOS 之 NSBundle 使用


    初学IOS开发的时候,经常看到这样的代码,

    [[NSBundle mainBundle] pathForResource:@"someFileName" ofType:@"yourFileExtension"]; 

    [YourViewController initWithNibName:"YourViewController" bundle:nil];

    一开始还不是很理解,通过google,慢慢的知道bundle在ios中的作用。

    Bundle是什么呢?bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in). 对应bundle,cocoa提供了类NSBundle.bundle中的有些资源可以本地化.例如,对于foo.nib,我们可以有两个版本: 一个针对英语用户,一个针对法语用户. 在bundle中就会有两个子目录:English.lproj和French.lproj,我们把各自版本的foo.nib文件放到其中. 当程序需要加载foo.nib文件时,bundle会自动根据所设置的语言来加载.

    //在程序中获得main bundle

    NSBundle bundle = [NSBundle mainBundle];  //很简单

    //一般我们通过这种方法来得到bundle.如果你需要其他目录的资源,可以指定路径来取得bundle

    NSBundle otherBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];

    //一旦我们有了bundle,就可以访问其中的资源文件了。

    NSString path = [otherBundle pathForImageResource:@"img"];

    NSImage img = [[NSImage alloc] initWithContentsOfFile:path];

    //bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类:

    Class newClass = [otherBundle classNamed:@"Person"];

    id person = [[newClass alloc] init];

    //如果不知到class名,也可以通过查找主要类来取得

    Class aClass = [otherBundle principalClass];

    id classInstance = [[aClass alloc] init];

    //可以看到, NSBundle有很多的用途.在这章中, NSBundle负责(在后台)加载nib文件. 我们也可以不通过NSWindowController来加载nib文件, 直接使用NSBundle:

    BOOL flag = [NSBundle loadNibNamed:@"ViewController" owner:someObject];

    //注意噢, 我们指定了一个对象someObject作为nib的File”s Owner

    获取XML文件
    NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];

    获取属性列表 
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];

  • 相关阅读:
    Linux OS共享文件
    源代码安装软件-MySQL
    细说Linux权限
    Linux进程作业的查看和杀死
    Linux_破解密码-营救模式
    找不同diff-打补丁patch
    WINDOWS自带md5校验工具
    猪,兔,等动物解剖平面图
    利用mimikatz破解远程终端凭据,获取服务器密码
    PHP中通过bypass disable functions执行系统命令的几种方式
  • 原文地址:https://www.cnblogs.com/chuang/p/2835224.html
Copyright © 2020-2023  润新知