1

我正在尝试将文件的内容传递到一个数组中,然后由随机图像生成器调用该数组。我错过了一些东西(或很多东西)。有任何想法吗?

NSString *chords = [[NSBundle mainBundle] pathForResource:@"ChordCharts" ofType:nil];

chordCharts = [NSMutableArray arrayWithContentsOfFile:chords];

int randomimages = rand() % 4;

switch (randomimages) {

    case 0:

        chordImage.image = [UIImage imageNamed:[chordCharts objectAtIndex:0]];

        break;

    case 1:

        chordImage.image = [UIImage imageNamed:[chordCharts objectAtIndex:1]];

        break;

    case 2:

        chordImage.image = [UIImage imageNamed:[chordCharts objectAtIndex:2]];

        break;

    case 3:

        chordImage.image = [UIImage imageNamed:[chordCharts objectAtIndex:3]];

        break;

    default:

        break;

}
4

1 回答 1

0

嗯,有什么问题?如果您希望文件看起来像这样

Name1.gif
Name2.jpg
...

那么它就行不通了;数组上的“initWithContentsOf”需要一个 plist 文件:

<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><array>
   <string>Name1.gif</string>
   <string>Name2.jpg</string>
   ...
</array></plist>

如果您想要文件的第一个版本,只需将文件读入字符串,然后使用 componentsSeparatedByString:@"\n" 将其拆分为行:

NSString* MyString=[NSString stringWithContentsOfFile:@"..."];
NSArray* chordCharts=[MyString componentsSeparatedByString:@"\n"];

您可能想要检查空行,并可能修剪这些行(以删除开头和结尾的空格)

于 2012-07-14T16:33:24.617 回答