TTTableViewController用对象数组变量填充dataSource

时间:2011-01-30 06:23:31

标签: iphone objective-c xcode ios three20

我使用TTTableViewController的示例来显示可以具有可变数量的行/图像/文本的数组。根据给出的示例,如果是ViewController,则在初始化期间对象列表是硬编码的,例如:

self.dataSource = [TTSectionedDataSource dataSourceWithObjects:
  @"Static Text",
  [TTTableTextItem itemWithText:@"TTTableItem"],
  [TTTableCaptionItem itemWithText:@"TTTableCaptionItem" caption:@"Text"],
  [TTTableSubtextItem itemWithText:@"TTTableSubtextItem" caption:kLoremIpsum],
  nil];

如果内容(我从另一个变量获得,比如上面示例中的kLoremIpsum)为空,我希望不显示一行。为此,我尝试过:

NSMutableArray * myListOfRows;
myListOfRows = [NSMutableArray arrayWithObjects:
  @"Static Text",
  [TTTableTextItem itemWithText:@"TTTableItem"],
  [TTTableCaptionItem itemWithText:@"TTTableCaptionItem" caption:@"Text"],
  nil];

if( kLoremIpsum != nil ) {
    [myListOfRows addObject:[TTTableSubtextItem
                             itemWithText:@"TTTableSubtextItem"
                                  caption:kLoremIpsum]];
}

self.dataSource = [TTSectionedDataSource dataSourceWithObjects:
  myListOfRows, 
  nil];

但是它不起作用,我的TTTableView仍然是完全空的。我可以看到该表正在使用我期望的对象数量。为什么这段代码不起作用?

1 个答案:

答案 0 :(得分:2)

最后,在您致电[TTSectionedDataSource dataSourceWithObjects:]的地方,您传递了myListOfRows,这是一个数组;但dataSourceWithObjects:函数需要传递实际对象,而不是指向对象的数组对象。

改为呼叫dataSourceWithArraysdataSourceWithItems。例如:

self.dataSource = [TTSectionedDataSource dataSourceWithArrays:@"Static Text",
                   myListOfRows, nil];

此外,在您要复制的原始示例中,@"Static Text"实际上不是一行,而是一个部分标题。因此,在您的代码中,您不会将此字符串添加到myListOfRows。换句话说,在代码开头附近,您应该删除@"Static Text"行:

myListOfRows = [NSMutableArray arrayWithObjects:
  // @"Static Text", // <-- commented out this line!
  [TTTableTextItem itemWithText:@"TTTableItem"],
  [TTTableCaptionItem itemWithText:@"TTTableCaptionItem" caption:@"Text"],
  nil];

初始化TTSectionedDataSource的这些不同方法记录在TTSectionedDataSource.h

/**
 * Objects should be in this format:
 *
 *   @"section title", item, item, @"section title", item, item, ...
 *
 * Where item is generally a type of TTTableItem.
 */
+ (TTSectionedDataSource*)dataSourceWithObjects:(id)object,...;

/**
 * Objects should be in this format:
 *
 *   @"section title", arrayOfItems, @"section title", arrayOfItems, ...
 *
 * Where arrayOfItems is generally an array of items of type TTTableItem.
 */
+ (TTSectionedDataSource*)dataSourceWithArrays:(id)object,...;

/**
 *  @param items
 *
 *    An array of arrays, where each array is the contents of a
 *    section, to be listed under the section title held in the
 *    corresponding index of the `section` array.
 *
 *  @param sections
 *
 *    An array of strings, where each string is the title
 *    of a section.
 *
 *  The items and sections arrays should be of equal length.
 */
+ (TTSectionedDataSource*)dataSourceWithItems:(NSArray*)items sections:(NSArray*)sections;