【问题标题】:populate UITableView填充 UITableView
【发布时间】:2012-11-01 19:01:14
【问题描述】:

我正在为我以前工作的 UITableView 苦苦挣扎,但不知何故我把它弄坏了! 它是 Paul Hegarty 课程单元的一部分

症状是视图加载但它是空的。我显然误解了一些相当基本的东西。

据我了解,两个关键方法是 1 节行数,在我的情况下返回零,我知道这是错误的!

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section


 {


 //   #warning Incomplete method implementation.
    // Return the number of rows in the section.
    NSLog(@"TopPlaces %@",self.topPlaces);
    //return 100;
    return [self.topPlaces count];

   }

由于上述原因,永远不会调用以下方法,因为没有行。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

第二个是在 ViewDidLoad 中,我可以在其中将数据记录到控制台,一切看起来都很好。即我的数据是在 ViewDidLoad 中生成的

- (void)viewDidLoad


 {
        [super viewDidLoad];

    dispatch_queue_t    dowloadQueue = dispatch_queue_create("flick downloader", NULL);
    dispatch_async(dowloadQueue, ^{
        NSArray *topPlaces = [FlickrFetcher topPlaces];
        //NSLog(@"Array is %@",topPlaces); // array is OK here
        dispatch_async(dispatch_get_main_queue(), ^{
            NSSortDescriptor *woeDescriptor = [[NSSortDescriptor alloc] initWithKey:@"_content" ascending:YES];  
            NSArray *woeDescriptors = @[woeDescriptor];
            NSArray *sortedReturns = [topPlaces sortedArrayUsingDescriptors:woeDescriptors];
            self.topPlaces = sortedReturns;
            //all the data is present here, count is 100 and array will log to console
           NSLog(@"count here is %u",[self.topPlaces count]);
        });
    });

    // Uncomment the following line to preserve selection between presentations.
    self.clearsSelectionOnViewWillAppear = NO;

}

【问题讨论】:

    标签: objective-c uitableview xcode4.5


    【解决方案1】:

    问题在于您进行了异步调用以获取数据(这意味着您的数组应该在将来的某个时间点充满数据),但之后您不会重新加载您的表格视图。调用reloadData 就可以了:

     ...            
    self.topPlaces = sortedReturns;
    //all the data is present here, count is 100 and array will log to console
    NSLog(@"count here is %u",[self.topPlaces count]);
    
    [self.tableView reloadData]; // Assuming that 'tableView' is your outlet
    

    这将指示您的 tableview 再次查询其数据源,并最终将所有数据加载到您的(现在非空的)topPlaces 数组中。


    进一步说明:

    我在@nerak99 的评论中看到他不完全确定为什么用reloadData 解决了这个问题。 好吧,我们举个例子:

    假设您有一家餐馆。

    您在早上 06:00 打开这个地方,发现您没有什么可做饭的。所以你要求你的一个人去市场购买供应品(那是你的异步调用)。

    同时你指示女服务员写今天的菜单,所以她写……嗯,什么都没有(那是你的 tableview 询问行数)。

    现在 07:00 去市场的人带着 10 件物品回来了。更新菜单的下一个合乎逻辑的步骤是什么?真正通知女服务员(即您的reloadData)您退回的物品。

    我希望这是有道理的:)

    【讨论】:

    • 喜欢与餐厅的类比。 +1。
    【解决方案2】:

    什么是 self.topPlaces?尝试 NSLog 数组并查看是否有任何内容。如果没有,请确保已设置。

    如果您提供更多信息,我将能够写一个更具体的答案。

    【讨论】:

    • 是的,我可以很好地记录内容。从上面提供和接受的答案中,我的理解是,因为我正在进行异步调用,所以 tableview 只是继续并加载,而该调用的结果没有在数组中。重新加载数据解决了这个问题,我不完全确定为什么,但你去吧。
    • @nerak99 查看我的进一步解释编辑。它应该让你明白。
    猜你喜欢
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多