【问题标题】:Hooking up JSON api to tableView without overloading在不重载的情况下将 JSON api 连接到 tableView
【发布时间】:2015-04-16 17:01:53
【问题描述】:

我创建了一个简单的 API,可以从数据库中检索所有新闻。但是我很困惑在不使用太多空间的情况下检索所有内容的最佳做法是什么?该数据库中有大量新闻,我想如果检索所有新闻并在 tableView 中显示它们对用户不利。所以我想当你滚动到按钮时,我需要为我的 tableView 加载更多功能?

到目前为止,我刚刚制作了这个检索所有新闻的函数,但是为了优化它,我的第一步是什么?

func getRecent(url: NSString) {

    let recentUrl = NSURL(string: url as String)
    var recentRequest = NSURLRequest(URL: recentUrl!)
    var recentData = NSURLConnection.sendSynchronousRequest(recentRequest, returningResponse: nil, error: nil)

    let jsonArray = JSON(data: recentData!)
    for (key: String, subJson: JSON) in jsonArray {
        // Create an object and parse your JSON one by one to append it to your array
        var newNewsObject = News(id: subJson["id"].intValue, title: subJson["title"].stringValue, link: subJson["url"].stringValue, imageLink: subJson["image_url"].stringValue, summary: subJson["news_text"].stringValue, date: getDate(subJson["date"].stringValue)) 
        recentArray.append(newNewsObject)
    }
    arrayNews.append(recentArray)
}

【问题讨论】:

    标签: ios objective-c json uitableview swift


    【解决方案1】:

    如果可能的话,创建一个在某些分页中响应新闻的函数[可选]

    你可以让表格查看你想要的分页大小,比如一次发布10条新闻,然后分页,然后你可以选择这样的方式

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1; 
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return [newsArray count]+1;   
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView
             cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *MyIdentifier = @"MyIdentifier";
    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        if (indexPath.row< newsArray.cout) {
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifier"];
            }
        }
        else {
              Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LoadingViewCell"];
              // add 10 more newsArray to the Array.
        }
    }
    

    希望能帮助到初级水平。

    HTH,享受编码!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多