如何从服务器上加载动态数据在uitableview上

问题描述:

我是初学者到ios开发,我需要从桌面视图上的服务器加载动态数据,如果有人知道代码请分享。如何从服务器上加载动态数据在uitableview上

在此先感谢, 安倍。

使用核心数据和NSFetchedResultsController,通过tableview控制器的委托方法填充NSFetchedResultsController实例的tableview。它反映了从数据库上自动删除,添加和任何类型的更新到tableview。

您可以使用ASIHTTPRequest库从服务器获取数据。你可以找到关于它的一些信息http://allseeing-i.com/ASIHTTPRequest/

你可以使用http://www.edumobile.org/iphone/iphone-programming-tutorials/how-to-use-tableview-in-iphone/这个链接来获得更多关于tableview的信息。

在链接的教程中,您必须在viewDidload方法中请求您的数据。

- (void)viewDidLoad { 

    // Request your data on this line. 
    /*NSArray *array = [[NSArray alloc]  initWithObjects:@"Sleepy",@"Sneezy",@"Bashful",@"Happy",@"Doc", 
         @"Grmpy",@"Dopey",@"Thorin",@"Dorin",@"Nori", 
         @"Ori",@"Balin",@"Dwalin",@"Fili",@"Kili",@"Oin",             
         @"Gloin",@"Bifur",@"Bofur",@"Bombur",nil ];*/ 

    self.listData = array; 
    [array release]; 
    [super viewDidLoad]; 
} 

所有这些都只是用法。你必须体验更多的例子来使用更复杂的情况。我将添加更多的教程代码从服务器获取数据并在tableview上显示。

实际上NSFetchedResultsController有点难于理解。

你应该尝试自己处理UITableView数据。看看UITableViewDelegate protocol

这里有一些步骤,你遵循:

1)创建一个类,将继承的UITableViewDelegate和UITableViewDataSource

@interface YourTableViewController: UITableViewController<UITableViewDelegate,UITableViewDataSource> 

2)创建一个数组,将保留您的数据

@property (nonatomic,retain) NSMutableArray *data; 

3)实现此方法:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
     DataObject *d=[data objectAtIndex:indexPath.row]; // selected data, now you can handle it   
    } 

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
     return data.count; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)mtableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
     NSString *[email protected]"CatalogCell";  
     UITableViewCell *cell=(UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:ident];  
     if (cell==nil) {   
      cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident] autorelease];   
     } 
     DataObject *d=[data objectAtIndex:indexPath.row]; 
     [cell.textLabel setText:d.someField];  
    } 

4)选择一些方法(NSURLConnection,ASIHTTPRequest(不好意思,只允许2的超链接对我来说)或其他)从服务器

-(void) parseData:(NSString *) d { 
    NSArray * parsedData=[self someMethodToParseData:d]; 
    [data setArray:parsedData]; 
    [tableView reloadData];  
} 

获取数据根据您的模型和复杂的层次您需要什么样的缓存策略,将表视图连接到远程数据源有不同的方法。这里会有很多事要说,但如果你是初学者,最适合你的就是看看互联网上的一些例子。

有一些“少数”的网络通信开源项目提供了很好的方法和很好的例子(包括源代码)来处理服务器驱动的应用程序。我举两个我喜欢:

  • AFNetworking:有例如与此库和的UITableViewController可能适合您的需要
  • RestKit来源:如果要映射,坚持服务器返回的数据,这将变成有用到本地模式。这可能需要更多的学习时间。

但是提醒你反正需要知道UITableView的基础知识和相关协议:UITableViewDelegateUITableViewDataSource。文档是可以的,但你甚至可能想看一下关于表格视图的WWDC 2011 podcast。而且,如果你还需要数据持久性,你应该开始考虑Core DataNSFetchedResultControllers,因为illis和Bogdan说,但事情会开始变得有点棘手。