【问题标题】:From NSArray to UILabel从 NSArray 到 UILabel
【发布时间】:2010-02-24 17:09:59
【问题描述】:

我的代码编译良好,但没有显示 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];
}

和:

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

谁能告诉我为什么?

【问题讨论】:

  • 您是否检查过以确保将文本正确加载到 mathsPracticText 中?
  • 什么是 mathsPractiveText?此外,如果您稍后再次加入,我也看不到拆分文件的目的

标签: objective-c cocoa-touch nsarray


【解决方案1】:

你的问题在于这条线

self.mathsPracticeText = mathsPracticeTextArray;

如果我理解正确, mathsPracticeText 是一个字符串。然后用这一行:

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

什么都不会发生,因为你试图将整个数组加载到一个字符串中,相反你应该做更多这样的事情:

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

【讨论】:

    【解决方案2】:

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

    您的代码中没有明显的其他错误,但这并不意味着一切都正确。例如,您没有发布 mathsPracticeText 的声明,但我认为它是 NSArray

    您对构造中的数组的摆弄有点过分了。您可以简单地使用从componentsSeparatedByString: 返回的数组,而不是从稍后发布的[fileContents componentsSeparatedByString:@" "] 构建第二个数组

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多