iOS開發區之NSBundle

原文鏈接:http://blog.sina.com.cn/s/blog_8c87ba3b0100t89v.html


bundle是一個目錄,其中包含了程序會使用到的資源. 這些資源包含了如圖像,聲音,編譯好的代碼,nib文件(用戶也會把bundle稱爲plug-in). 對應bundle,cocoa提供了類NSBundle.

我們的程序是一個bundle. 在Finder中,一個應用程序看上去和其他文件沒有什麼區別. 但是實際上它是一個包含了nib文件,編譯代碼,以及其他資源的目錄. 我們把這個目錄叫做程序的main bundle

bundle中的有些資源可以本地化.例如,對於foo.nib,我們可以有兩個版本: 一個針對英語用戶,一個針對法語用戶. 在bundle中就會有兩個子目錄:English.lproj和French.lproj,我們把各自版本的foo.nib文件放到其中. 當程序需要加載foo.nib文件時,bundle會自動根據所設置的語言來加載. 我們會在16章再詳細討論本地化

通過使用下面的方法得到程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];

一般我們通過這種方法來得到bundle.如果你需要其他目錄的資源,可以指定路徑來取得bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];

一旦我們有了NSBundle 對象,那麼就可以訪問其中的資源了
// Extension is optional
NSString *path = [goodBundle pathForImageResource:@"Mom"];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];

bundle中可以包含一個庫. 如果我們從庫得到一個class, bundle會連接庫,並查找該類:
Class newClass = [goodBundle classNamed:@"Rover"];
id newInstance = [[newClass alloc] init];

如果不知到class名,也可以通過查找主要類來取得
Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];

可以看到, NSBundle有很多的用途.在這當中, NSBundle負責(在後臺)加載nib文件. 我們也可以不通過NSWindowController來加載nib文件, 直接使用NSBundle:
BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];
注意噢, 我們指定了一個對象someObject作爲nib的File's Owner

 

 
使用initWithContentsOfFile時,文件路徑的寫法 使用initWithContentsOfFile方法可以通過讀取一個文件的內容來初始化對象。 但文件的路徑應該怎麼確定呢? 可以使用NSBundle的對象來獲取。 例如當前程序所在目錄下有個文件re.xml,我們要將該文件的內容做爲NSData的數據源來初始化一個NSData對象,可以用下面的方法來實現:
 
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"]; NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
 
讀取plist中的內容:
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; self.data = [NSArrayarrayWithContentsOfFile:dataPath];
 
刪除本地文件
NSString * thePath=[self getUserDocumentDirectoryPath];
NSMutableString * fullPath=[[[NSMutableString alloc]init]autorelease];
[fullPath appendString:thePath];
NSString * idString=[idArray objectAtIndex:indexPath.row];
NSString * coverName=[NSString stringWithFormat:@"/%@.jpg",idString];
[fullPath appendString:coverName];
NSFileManager *defaultManager;
defaultManager = [NSFileManager defaultManager];
 
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error BOOL boolValue=[defaultManager removeItemAtPath: fullPath error: nil];
 
if (boolValue) {
NSLog(@"remove cover image ok");
}
 
- (NSString*)getUserDocumentDirectoryPath {
NSArray* array = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
 
if([array count])
return [array objectAtIndex: 0];
else return @"";
 
}
發佈了45 篇原創文章 · 獲贊 21 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章