2010-01-11 29 views
0

我是一个开始的iPhone SDK程序员。我构建了一个简单的练习应用程序,我试图用来了解更多关于表格视图的信息。这是一个应用程序,从plist中加载足球队,并以球场名称和徽标以表格形式显示。攻击团队进入该团队的详细视图。添加部分到Xcode的plist用于可可触摸表视图

我想了解如何节添加到这一点,所以我可能有一对夫妇在一节团队和他人在另一部分的等

我想我需要既重结构我的plist并更改代码以从plist的不同级别读取数组?

首先,我有一个plist,包含3个词典的根数组,每个团队一个。每个字典有3个键,“名称”,“体育场”和“标志”。这工作正常。我通过加载它:

NSString *path = [[NSBundle mainBundle] pathForResource:@"teams" ofType:@"plist"]; 
teams = [[NSMutableArray alloc] initWithContentsOfFile:path]; 

然后

// Configure the cell. 
NSDictionary *team = [teams objectAtIndex:indexPath.row]; 
cell.textLabel.text = [team objectForKey:@"name"]; 
NSString *imgPath = [team valueForKey:@"logo"]; 
cell.imageView.image = [UIImage imageNamed:imgPath]; 
cell.detailTextLabel.text =[team objectForKey:@"stadium"]; 
return cell; 

没问题。但现在我想要的部分,所以我改变了我的plist到:

<array> 
<dict> 
    <key>teams 1</key> 
    <array> 
     <dict> 
      <key>name</key> 
      <string>Packers</string> 
      <key>stadium</key> 
      <string>Lambeau Field</string> 
      <key>logo</key> 
      <string>packers.jpg</string> 
     </dict> 
     <dict> 
      <key>name</key> 
      <string>Jets</string> 
      <key>stadium</key> 
      <string>Giants Stadium</string> 
      <key>logo</key> 
      <string>jets_logo.jpg</string> 
     </dict> 
    </array> 
</dict> 
<dict> 
    <key>teams 2</key> 
    <array> 
     <dict> 
      <key>name</key> 
      <string>Cincinnati Bengals</string> 
      <key>stadium</key> 
      <string>Paul Brown Stadium</string> 
      <key>logo</key> 
      <string>bengals.jpg</string> 
     </dict> 
    </array> 
</dict> 

而且我不确定如何修改viewDidLoad中分配的部分,以一个的NSArray和团队“级别”到另一个阵列。

回答

0

首先,您需要使用数组作为数据结构的前两个级别。字典是无序的,因此很难将它们用作表格格式的数据源。将它们用于单个单元格中显示的每条记录的数据是很好的。要将字典作为表格格式数据使用,您必须将其密钥存储到数组中,以便每个密钥都有一个特定的数字索引,以供表格用来查找密钥。

你会需要这样的东西在你的UITabelViewDataSource类以下内容:

@property(nonatomic, retain) NSArray *sectionNames; 
... 
NSArray *sectionNames=[teams allKeys]; 

在你UITabelViewDataSource类,你需要这些方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return [self.sectionNames count]; 
} 

这将返回在桌子部分的数量,其在你的情况下代表顶级字典中的对象数量。

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{ 
    return [[teams valueForKey:[self.sectionNames objectAtIndex:section] count]; 
} 

这将返回其在你的情况下,意味着对象的每个第二电平字典返回存储在每个sectionName元素的键的数目在每个部分中的行数。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{ 
     return [self.sectionNames objectAtIndex:section]; 
} 

这将返回将显示每个节标题的名称,在您的情况下是每个第一级字典值的关键。

除非您特别需要按键引用各部分,否则应该考虑将除团队数据以外的所有内容都存储在数组中而不是字典中。它会让你的表更容易实现。