阅读&使用Xcode编写包含Dictionary字典的Plist

时间:2011-07-18 05:48:02

标签: xcode nsmutablearray plist nsmutabledictionary

这是我的问题,我正在尝试创建一个UITableView,它能够将我的plist中的Name显示到单元格中。我无法从Plist中获取名称。我想我不太确定提取信息所需的编程代码。

如果您可以通过提供一个好的教程或示例代码来提供帮助,那就太棒了。谢谢!

<array>
    <dict>
        <key>Name</key>
        <string>Device 2</string>
    </dict>
    <dict>
        <key>Name</key>
        <string>Device 1</string>
    </dict>
</array>

这些代码在我的viewDidLoad ..

NSBundle *bundle = [NSBundle mainBundle];

    NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSLog(@"The file exists");
    } else {
        NSLog(@"The file does not exist");
    }

    contentDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    NSLog(@"The count: %i", [contentDict count]);
    contentArray = [NSMutableArray arrayWithContentsOfFile:path];
    NSLog(@"The array: %i", [contentArray count]);
    [contentArray retain];
    [contentDict retain];
    [mainTableView reloadData];

这些在我的tableView ..

static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]autorelease];
    }

    cell.textLabel.text = [sortedArray objectForKey:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;

1 个答案:

答案 0 :(得分:4)

也许你想在viewDidLoad中尝试以下内容:

NSBundle *bundle = [NSBundle mainBundle];

    NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSLog(@"The file exists");

    self.contentArray = [NSMutableArray arrayWithContentsOfFile:path];
    NSLog(@"The array: %i", [contentArray count]);

    [mainTableView reloadData];
}

请注意,contentArray应该是一个retain属性,然后是cellForRowAtIndexPath方法:

NSDictionary *dict = [self.contentArray objectAtIndex:indexPath.row];
cell.textLabel.text = (NSString*)[dict objectForKey:@"Name"];

希望这会有所帮助......