1

我想首先说我对编码有点陌生,但我很高兴学习。我试图让标签循环遍历字母表的前四个字母,这些字母作为字符串存储在 .plist 文件中。每次按下按钮时,该值都会切换。

这是plist的源代码:

<dict>
<key>0</key>
<string>A</string>
<key>1</key>
<string>B</string>
<key>2</key>
<string>C</string>
<key>3</key>
<string>D</string>

我将键设为整数,以便我可以使用以下代码轻松地循环遍历这些值:

- (void)buttonPressed:(id)sender {
int x = 0;
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
theLabel_.text = [dict objectForKey:x];
x++;
}

这根本行不通。我怀疑问题出在我更改标签文本的那一行。我不相信我在整数值中正确使用了“objectForKey”语句。我应该如何使用整数作为访问 plist 数据的键?

4

1 回答 1

0

Property list dictionaries use strings as keys so you'd have to make strings out of your integer indexes:

theLabel_.text = [dict objectForKey:[NSString stringWithFormat:@"%d", x]];

A better way might be to use an array instead (also a plist object). Then all you'd have to change would be the access method:

NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
theLabel_.text = [array objectAtIndex:x];

Your plist file would look like:

<array>
    <string>A</string>
    <string>B</string>
    <string>C</string>
    <string>D</string>
</array>
于 2013-06-18T17:56:59.730 回答