从plist输出数据到NSString

han*_*Dev 0 iphone objective-c nsstring ios

我正从plist中提取一些字符串数据:

<dict>
<key>Feb 7, 2000</key>
<array>
    <string>7</string>
    <string>8</string>
</array>
<key>Jan 27, 2001</key>
<array>
    <string>8</string>
    <string>7</string>
</array>
Run Code Online (Sandbox Code Playgroud)

并使用以下代码输出UILabel中的数据:

  NSString * myString = [NSString stringWithFormat:@"%@",self.data];

    myLabel.text = myString;
Run Code Online (Sandbox Code Playgroud)

输出显示为 ( 7, 8)

有没有人知道如何删除括号和逗号.并分离值,以便我可以显示类似的东西first: 7 second: 8

Ann*_*nne 5

例:

<dict>
<key>Feb 7, 2000</key>
<array>
    <string>7</string>
    <string>8</string>
</array>
<key>Jan 27, 2001</key>
<array>
    <string>8</string>
    <string>7</string>
</array>
</dict>
Run Code Online (Sandbox Code Playgroud)

码:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 

for(id key in dict) {
    NSLog(@"First:%@ Second:%@", [[dict objectForKey:key] objectAtIndex:0],  [[dict objectForKey:key] objectAtIndex:1]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

First:7 Second:8
First:8 Second:7
Run Code Online (Sandbox Code Playgroud)


编辑 (回复评论)

首先,您需要确定内部的密钥NSMutableDictionary.
加载.plist文件,循环并将密钥添加到NSMutableArray.

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 
NSMutableArray *keys = [[NSMutableArray alloc] init];
for(id key in dict) [keys addObject:[NSString stringWithFormat:@"%@",key]];
Run Code Online (Sandbox Code Playgroud)

确保可以访问该阵列UIPickerView.
UIPickerView应能够检索到这样的键:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [keys objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [keys count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

最后,更新UILabel如下:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    theLabel.text = [NSString stringWithFormat:@"First:%@ Second:%@", 
                      [[dict objectForKey:[keys objectAtIndex:row]] objectAtIndex:0],  
                      [[dict objectForKey:[keys objectAtIndex:row]] objectAtIndex:1]];
}
Run Code Online (Sandbox Code Playgroud)

UIPickerView现在包含以下行:

Feb 7, 2000
Jan 27, 2001
Run Code Online (Sandbox Code Playgroud)

例如,当选择"2001年1月27日"时,UILabel显示:

First:8 Second:7
Run Code Online (Sandbox Code Playgroud)

  • 添加了一些额外的代码,希望这有助于:) (2认同)