2014-10-13 61 views
0

在Objective C,我有somethng這樣的:NSInputStream閱讀:最大長度:無法讀取數據,返回-1

uint8_t f[400000]; 
NSString *Str; 
unsigned int count = 0; 
NSError* error = nil; 
Str = [[NSString alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Test" ofType:@"txt"] encoding:NSUTF8StringEncoding error:&error]; 
@try { 
    NSInputStream *fin = [NSInputStream inputStreamWithData:[Str dataUsingEncoding:NSUTF8StringEncoding]]; 
    count = [fin read:f maxLength:400000]; 

} 
@catch (NSException * e) { 
    NSLog(@"Exception: %@", e); 
} 
@finally { 
    NSLog(@"finally"); 
} 

我轉換nsstringnsinputstream,然後嘗試讀取內容

但在我調試代碼之後,count中有-1,即在讀取時發生錯誤。我不明白我在這裏做錯了什麼!有人能幫助我嗎?

注意Test.txt是內容的純文本文件只是「你好」和調試顯示Str被初始化與內容。這意味着在try區塊中出現問題。

任何幫助表示讚賞。

+1

我相信*您需要設置委託並在運行循環中安排輸入流([見本文])(https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/流/用品/ ReadingInputStreams.html))。改爲使用「NSFileManager」。 – Droppy

+0

是的,它訣竅 – Sibir

+0

也創建一個400K'自動'變量是一個壞主意;-) – Droppy

回答

1

您沒有打開該流。您無法先讀取/寫入NSStreamNSInputStreamNSOutputStream都是NSStream的兩個子類),而無需先打開它。在讀取流對象之前,請先致電open