从主文件包加载数据

问题:

  你已经在 Xcode 中添加了一些资源(例如图片),现在,在运行时,你希望访问这些资源。 

方法:

  使用 NSBundle 类中的 mainBundle 类方法来访问主文件包。一旦这个步骤完成,使用 pathForRecource: ofType:方法从主文件包中获得具体资源的路径,路径明确之后,根据资 源的类别可以获取具体文件,比如 UIImage 或者 NSData,或者通过 NSFileManager 手动获取文件。

例子:

  找到指定文件做一些处理

[[NSBundle mainBundle] pathForResource:@"AlanSugar"
ofT ype:@"png"];
if ([alanSugarFilePath length] > 0){
UIImage *image = [UIImage imageWithContentsOfFile:alanSugarFilePath];
if (image != nil){
NSLog(@"Successfully loaded the file as an image.");
} else {
NSLog(@"Failed to load the file as an image.");
}
} else {
NSLog(@"Could not find this file in the main bundle.");
}
//找到指定文件存入内存
[[NSBundle mainBundle] pathForResource:@"AlanSugar" ofT ype:@"png"]; if ([alanSugarFilePath length] > 0){ NSError *readError = nil; NSData *dataForFile = [[NSData alloc] initWithContentsOfFile:alanSugarFilePath options:NSMappedRead error:&readError]; if (readError == nil && dataForFile != nil){ NSLog(@"Successfully loaded the data."); } else if (readError == nil && dataForFile == nil){ NSLog(@"No data could be loaded."); } else { NSLog(@"An error occured while loading data. Error = %@", readError); } } else { NSLog(@"Could not find this file in the main bundle."); }

 

posted @ 2014-10-08 13:00  safiri  阅读(142)  评论(0编辑  收藏  举报