【问题标题】:Read & write my Plist that has an Array of Dictionary using Xcode使用 Xcode 读取和写入具有字典数组的 Plist
【发布时间】:2011-07-18 05:48:01
【问题描述】:

这是我的问题,我正在尝试创建一个 UITableView,它能够将我的 plist 中的名称显示到单元格中。我无法从 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;

【问题讨论】:

    标签: xcode nsmutablearray plist nsmutabledictionary


    【解决方案1】:

    也许您想在 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 应该是一个保留属性,然后在 cellForRowAtIndexPath 方法中:

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

    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2018-08-25
      • 2015-02-14
      • 2012-07-14
      相关资源
      最近更新 更多