2010-02-24 64 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:@" "]; 
}