plist类型:字典到UITableView

时间:2013-10-12 09:40:15

标签: uitableview dictionary plist

我的“Property List2”如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Police</key>
    <dict>
        <key>UserName</key>
        <string>PoliceStation</string>
        <key>Image</key>
        <string>PoliceStation.png</string>
        <key>Number</key>
        <string>1241241244</string>
        <key>Address</key>
        <string>TaichungNorth</string>
    </dict>
        <key>Fire</key>
    <dict>
        <key>UserName</key>
        <string>FireFighter</string>
        <key>Image</key>
        <string>FireFighter.png</string>
        <key>Number</key>
        <string>21324124</string>
        <key>Address</key>
        <string>TaichungEast</string>
    </dict>
        <key>Taichung</key>
    <dict>
        <key>UserName</key>
        <string>TaichungGovernment</string>
        <key>Image</key>
        <string>TaichungGovernment.jpg</string>
        <key>Number</key>
        <string>3252342342</string>
        <key>Address</key>
        <string>TaichungWest</string>
    </dict>
    </dict>
</plist>

如何将每个“UserName”和“Image”加载到UITableView中?特别是当类型为“字典”而不是“数组”时?

UITableview将在Center中显示每个“UserName”文本,在左侧显示每个“Image”。

1 个答案:

答案 0 :(得分:0)

您可以将plist解析为dictonary:

NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"plist"];  
NSDictionary *objects = [NSDictionary dictionaryWithContentsOfFile:path];

您可以迭代所有键并创建用于在表视图中显示的对象:

NSMutableArray *parsedObjects = [NSMutableArray array];
[objects enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    Object *object = [[Object alloc] init];
    [object setUserName:obj[@"UserName"]];
    ...
    [parsedObjects addObject:object];
}];

比你应该实现tableView:cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {
     ...
     Object *object = parsedObjects[indexPath.row];
     [cell setObject:object];

     return cell;
  }

并实现在单元格中显示的数据。