如何在Swift中将数据从NSArray传输到字符串?

问题描述:

我必须把数据放在tableview中,但即使很难从JSON获取信息,我也无法将数据传递给postTitle变量。这是为什么?这里是我的代码:如何在Swift中将数据从NSArray传输到字符串?

import UIKit 

class ViewController: UIViewController, UITableViewDelegate,  UITableViewDataSource { 

var postTitle = [AnyObject]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json" 

    //  https://hacker-news.firebaseio.com/v0/item/9324191.json 

    if let url = NSURL(string: baseURL) { 
     var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in 

      if error != nil { 
       println("Error: \(error.localizedDescription)") 
      } else { 
       var jsonError: NSError? 
       if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSArray { 

         self.postTitle.append(topStories) 

       } 


      } 

     }) 


     taskURL.resume() 

    } 


} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    println(postTitle.count) 
    return postTitle.count 
} 



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = UITableViewCell() 

    println(self.postTitle) 
    // cell.textLabel?.text = postTitle[indexPath.row] 
    return cell 
} 




override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 
+0

你看到什么错误? – 2015-04-05 21:01:55

+0

你知道'dataTaskWithURL()'**异步工作**吗? - 请参阅http://stackoverflow.com/questions/28782932/tableview-is-not-updating-until-i-tap-another-tab-and-get-back-swift,或搜索“从异步中获取值功能”。 – 2015-04-05 21:11:23

所以来自Reddit的其他人帮助我。我错过了几件事。首先是数据类型Int,它需要传递给实例变量,其次是UITableView:这里是工作解决方案。希望这会帮助某人。

进口的UIKit

类的ViewController:UITableViewController中,的UITableViewDelegate,UITableViewDataSource {

var postTitles = [Int]() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json" 


    if let url = NSURL(string: baseURL) { 
     var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in 

      if error != nil { 
       println("Error: \(error.localizedDescription)") 
      } else { 
       var jsonError: NSError? 
       if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? [Int] { 
         self.postTitles = Array(topStories[0...9]) 

         // Reload the table with our new results! 
         self.tableView.reloadData() 
       } 
      } 

     }) 

     taskURL.resume() 

    } 
} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return postTitles.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell 


    let postTitle = String(self.postTitles[indexPath.row]) 

    cell.textLabel?.text = postTitle 

    return cell 
    } 
} 

topStoriesNSArray,但你是追加到postTitle阵列(它的类型是[AnyObject]的)。 Array.append将单个项目添加到数组中。因此,您将在postTitle阵列中添加一个条目(NSArray)。

我猜你想要的是将topStories的内容添加到postTitle?在这种情况下你要使用的extend而非append方法:

self.postTitle.extend(topStories) 
+0

或者使用'+ ='语法:'self.postTitle + = topStories' – 2015-04-05 22:14:45

+0

问题是我有这个函数返回我的0,即使把@Airspeed Velocity建议。 'FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - >诠释{ 的println(postTitle.count) 回报postTitle.count } ' – 2015-04-06 08:42:08

既然你显然重装所有的冠军对每个请求,你可以很容易地做到这一点:self.titles = topStories

我刚建这样的测试应用程序,它工作得很好。

PS:self.postTitle.append无论如何都会产生错误的结果,因为它也会在您的数组中添加标题。你可能应该使用的方法是self.postTitle.join,因为它使用交集。

+0

它没有工作。没有任何内容存储在postTitle变量中,但是如果在JSONSerialization之后println(self.postTitles),它会将值存储在该变量中。我不明白。 – 2015-04-06 10:57:27

+0

这里是[我的工作代码的要点](https://gist.github.com/Jan0707/b401441ee65c7a26f485) – Jan 2015-04-06 12:30:43

+0

如果我为你编码的话,请如此善良,并将我的答案标记为已接受的答案。 – Jan 2015-04-06 18:44:26