开发者

From NSArray to UILabel

开发者 https://www.devze.com 2022-12-20 23:13 出处:网络
My code compiles fine but doesn\'t show the text from mathspractice.txt -(void)loadText { NSBundle *bundle = [NSBundle mainBundle];

My code compiles fine but doesn't show the text from mathspractice.txt

-(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];
}

and:

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

can any开发者_JAVA技巧one tell me why?


Your problem lies with the line

self.mathsPracticeText = mathsPracticeTextArray;

If I understand correctly mathsPracticeText is a string. Then with this line:

myLabel.text = [mathsPracticeText componentsJoinedByString:@" "];

nothing will happen because you tried to load the entire array into a string, instead you should do something more like this:

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

and

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


In Cocoa Touch, there’s no +[NSString stringWithContentsOfFile:] (and on the desktop it’s deprecated). You have to use stringWithContentsOfURL:encoding:error:.

There’s no obvious other error in your code, but that doesn’t mean that everything is right. You didn’t post the declaration of mathsPracticeText, for instance, but I assume it’s an NSArray.

You’re fiddling a little too much with the arrays in the construction. Instead of building a second array from [fileContents componentsSeparatedByString:@" "] which you later release, you could simply use the one returned from componentsSeparatedByString:

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

精彩评论

暂无评论...
验证码 换一张
取 消