2011-06-14 50 views
0

我想打開一個小文本文件來測試文件上的一些NSFileHandle函數。但是我無法弄清楚如何做到這一點,如果你能告訴我我錯過了什麼會很棒。如何用NSFileHandle打開文本文件

//.h

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> { 
    NSFileHandle *nCode; 
} 
@property (nonatomic, retain) IBOutlet NSFileHandle *nCode; 

- (IBAction)showInfo:(id)sender; 

//check for code 
- (void)fetchCode:(id)sender; //this function is attached to a button in the .nib 

@end 

//.m

- (void)fetchCode:(id)sender{ 
nCode = [NSFileHandle fileHandleForReadingAtPath:@"nCode01.txt"]; 

if (nCode == nil) { 
    NSLog (@"Open of nCode for reading failed\n"); 
    return; 
} 

[nCode closeFile]; 
} 

所有我在這裏做的是試圖打開該文件,但我每次按下按鈕時,我recive錯誤信息「打開nCode閱讀失敗」......我做錯了什麼?

從這我希望找到一種方法,讓用戶輸入一個數字代表文本文件中的一行,然後返回該行中的文本..劑量任何人都知道這樣做的方式?可能嗎?

+0

我已經把它變成我的資源文件,在我的文件包中 – tinhead 2011-06-14 22:51:18

回答

3

最有可能的問題是文件路徑,因爲你沒有指定完整的路徑名。當你想訪問你的應用程序包中的文件,使用-[NSBundle pathForResource:ofType]

NSString *path = [[NSBundle mainBundle] pathForResource:@"nCode01" 
               ofType:@"txt"]; 
nCode = [NSFileHandle fileHandleForReadingAtPath:path]; 
+0

編曲......我看到不好受,這是初始化,當你做同樣的事情一個數據庫...我應該知道這個..對於目標C來說還是新的,但是yea似乎很難錯過.. :(謝謝你。 – tinhead 2011-06-14 23:02:21