在讀取本地文件時(shí),我們一般都會(huì)直接考慮到NSBundle,因?yàn)樗侵府?dāng)前目錄,而通常我們有時(shí)也會(huì)考慮到NSSearchPathForDirectoriesInDomains來(lái)獲取程序目錄,從而達(dá)到讀取某一指定文件。
1、使用NSBundle讀取文件
//dataPath 表示當(dāng)前目錄下指定的一個(gè)文件 data.plist
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"Data.plist" ofType:nil];
// 如果plist文件中ROOT的類型是Array
NSArray *array = [NSArray arrayWithContentsOfFile:dataPath];
// 如果plist文件中ROOT的類型為Dictionary
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:dataPath];
2、直接使用NSSearchPathForDirectoriesInDomains讀取文件
//filePath 表示程序目錄下指定文件
NSString *filePath = [self documentsPath:@"usefile.txt"];
- (NSString *)documentsPath:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDitectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObjects];
return [documentsDiretory stringByAppendingPathComponent:fileName];
}
注意點(diǎn),在這里文件名可能在賦值的時(shí)候不知不覺(jué)就添加進(jìn)了前后不必要的空格,因此在讀取文件指定目錄時(shí),需要將它去空格:
// 去左右空格
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
// 去掉所有不必要的空格
NSString *strUrl = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""];
我們?cè)诳偨Y(jié)的時(shí)候,適當(dāng)?shù)目梢允褂靡韵路椒▉?lái)討論或解決問(wèn)題:
【問(wèn)題分析】
1、使用NSString中stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]方法只是去掉左右兩邊的空格;
2、使用NSString *strUrl = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""];可以去掉空格,注意此時(shí)生成的strUrl是autorelease屬性的,不要妄想對(duì)strUrl進(jìn)行release操作。
【問(wèn)題小結(jié)】
用stringByReplacingOccurrencesOfString方法去掉空格,實(shí)際上只是做了字符替換操作,除了空格還可以替換其它字符。目前該方法只使用了一次,還不能確定該方法的副作用。
// 在讀文件時(shí),看文件的根目錄是什么類型的,然后用什么類型來(lái)接住它。

就比如說(shuō)圖1,需要用到字典類型來(lái)接住它。
NSDictionary