NSTableView有比NSOutlineView使用起来要简单。

下面介绍一个简单用法。

这里简单使用一下dataSource就行了。

在AppDelegate里实现:

 

  1. -(void)awakeFromNib 
  2.     NSTableColumn * columnCompany = [[NSTableColumn alloc] initWithIdentifier:@"2"].autorelease; 
  3.     [_table addTableColumn:columnCompany]; 
  4.     NSInteger columnCount = [[_table tableColumns] count]; 
  5.     for (int i = 0; i< columnCount; i++)  
  6.     { 
  7.         [[[_table tableColumns] objectAtIndex:i] setIdentifier:[NSString stringWithFormat:@"%d",i]]; 
  8.     } 

这里_table是一个NSTableView的一个Outlet.它默认有两列,这里自己加一列。形成三列。

然后设置identify.这个identifier属性文档里有说明。

identifier

Returns the object used by the data source to identify the attribute corresponding to the receiver.

为dataSource提供标志column的一个属性id.但是文档没说是NSString类型的。我想它应该是NSString类型的吧。

在DataSource里实现

 

  1. -(void)awakeFromNib 
  2.     self.doc = [[NSXMLDocument alloc] initWithData:[NSData dataWithContentsOfFile:@"tableSource.xml"] options:1<<10 error:nil]; 
  3.  
  4.  
  5. -(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView 
  6.     return [self.doc.rootElement childCount]; 
  7.  
  8. -(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row 
  9.     NSInteger columnIndex = [[tableColumn identifier] intValue]; 
  10.     return [[[self.doc.rootElement childAtIndex:row] childAtIndex:columnIndex] stringValue]; 

这里xml内容是:

 

  1. <products> 
  2.     <product> 
  3.         <name>iPhone</name> 
  4.         <price>4,500</price> 
  5.         <company>apple</company> 
  6.     </product> 
  7.     <product> 
  8.         <name>Android</name> 
  9.         <price>2,000</price> 
  10.         <company>google</company> 
  11.     </product> 
  12.     <product> 
  13.         <name>N99</name> 
  14.         <price>1,500</price> 
  15.         <company>Nokia</company> 
  16.     </product> 
  17. </products> 

显示结果:

 

NSTableView使用笔记(二)_NSTableView