在工程中加入一個文字文件,例如 aa.txt,內容可以是任意文字。接下來分別用 NSBundle 與 NSURL 讀取內容。
NSString *pathBundle = [[NSBundle mainBundle] pathForResource:@"aa" ofType:@"txt"]; NSString *outstringbundle = [NSString stringWithContentsOfFile:pathBundle encoding:NSUTF8StringEncoding error:nil]; NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"aa" withExtension:@"txt" subdirectory:nil]; NSString *outstringUrl = [NSString stringWithContentsOfURL:pathUrl encoding:NSUTF8StringEncoding error:nil];
兩種方式都能取得相同內容。NSBundle 主要用於取得應用內資源路徑,NSURL 則以 URL 形式表示資源位置。
可以先建立一個新文件路徑,再使用 NSFileManager 建立文件。
NSString *newPath = [NSString stringWithFormat:@"%@/Documents/New", NSHomeDirectory()]; NSString *newfile = [NSString stringWithFormat:@"%@/new.mp3", newPath]; [[NSFileManager defaultManager] createFileAtPath:newfile contents:nil attributes:nil];
接著用 NSData 讀取原始文件數據,再寫入新文件。
NSData *data = [[NSData alloc] initWithContentsOfFile:pathBundle]; [data writeToFile:newfile atomically:YES];
透過這個小範例,可以清楚區分 NSBundle 與 NSURL 在文件路徑處理上的差異。