2010-02-24 65 views
0

我的代碼編譯罰款,但沒有顯示從mathspractice.txt從NSArray的到的UILabel

-(void)loadText 
{ 
NSBundle *bundle = [NSBundle mainBundle]; 
NSString *textFilePath = [bundle pathForResource:@"mathspractice" ofType:@"txt"]; 
NSString *fileContents = [NSString stringWithContentsOfFile:textFilePath]; 
NSArray *mathsPracticeTextArray = [[NSArray alloc] initWithArray:[fileContents componentsSeparatedByString:@" "]]; 
self.mathsPracticeText = mathsPracticeTextArray; 
[mathsPracticeTextArray release]; 
} 

和文本:

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,100,960,40)]; 
myLabel.text = [mathsPracticeText componentsJoinedByString:@" "]; 
[myScrollView addSubview:myLabel]; 
[myLabel release]; 

誰能告訴我爲什麼?

+0

回到你檢查,以確保文本被正確地加載到mathsPracticText? – kubi 2010-02-24 17:11:52

+0

什麼是mathsPractiveText?另外我沒有看到分割文件的目的,如果你只是稍後再加入它們 – 2010-02-24 17:20:25

+0

Duplicate:http://stackoverflow.com/questions/2327656/parsing-txt-from-array-to-uilabel – 2010-02-24 19:03:21

回答

1

你的問題在於線

self.mathsPracticeText = mathsPracticeTextArray; 

如果我理解正確mathsPracticeText是一個字符串。然後用這條線:

​​

什麼都不會發生,因爲你試圖將整個數組加載到一個字符串,而不是你應該做更多的東西是這樣的:

-(void)loadText 
{ 
NSBundle *bundle = [NSBundle mainBundle]; 
NSString *textFilePath = [bundle pathForResource:@"mathspractice" ofType:@"txt"]; 
NSString *fileContents = [NSString stringWithContentsOfFile:textFilePath]; 
mathsPracticeText = fileContents; 
[mathsPracticeTextArray release]; 
} 

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,100,960,40)]; 
[myLabel setText:mathsPracticeText]; 
[myScrollView addSubview:myLabel]; 
[myLabel release]; 
1

在Cocoa Touch中,沒有+[NSString stringWithContentsOfFile:](在桌面上它已被棄用)。你必須使用stringWithContentsOfURL:encoding:error:

代碼中沒有明顯的其他錯誤,但這並不意味着一切都是正確的。例如,您沒有發佈mathsPracticeText聲明,但我認爲它是NSArray

您在構造中的陣列中擺弄得太多了。相反,從建立一個[fileContents componentsSeparatedByString:@" "]第二陣列,你以後釋放的,你可以簡單地用一個從componentsSeparatedByString:

-(void)loadText 
{ 
    NSString *textFilePath = [[NSBundle mainBundle] pathForResource:@"mathspractice" ofType:@"txt"]; 
    NSString *fileContents = [NSString stringWithContentsOfFile:textFilePath 
                 encoding:NSUTF8StringEncoding 
                  error:NULL]; 
    self.mathsPracticeText = [fileContents componentsSeparatedByString:@" "]; 
}