0

I got an error in self.tableView.reloadData(). Can it be because I use the SSASideMenu lib, where there are no segues between the menu and other views? To me, it seems like my tableView was not initialized.

class GroupListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var TableData:Array< String > = Array < String >()

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")

    title = "title"
    var menuImage:UIImage = UIImage(named: "sidebtn")!
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "1", style: .Plain, target: self, action: "presentLeftMenuViewController")
    menuImage = menuImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    self.navigationItem.leftBarButtonItem?.image = menuImage



    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return TableData.count
}

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = TableData[indexPath.row]
    return cell
}
func get_data_from_url(url:String)
{
    let httpMethod = "GET"
    let timeout = 15
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!,
        cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(
        urlRequest,
        queue: queue,
        completionHandler: {(response: NSURLResponse!,
            data: NSData!,
            error: NSError!) in
            if data.length > 0 && error == nil{
                let json = NSString(data: data, encoding: NSASCIIStringEncoding)
                self.extract_json(json!)
            }else if data.length == 0 && error == nil{
                println("Nothing was downloaded")
            } else if error != nil{
                println("Error happened = \(error)")
            }
        }
    )
}
func extract_json(data:NSString)
{
    var parseError: NSError?
    let jsonData:NSData? = data.dataUsingEncoding(NSASCIIStringEncoding)!
    let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &parseError)
    if (parseError == nil)
    {
        if let countries_list = json as? NSArray
        {
            for (var i = 0; i < countries_list.count ; i++ )
            {
                if let country_obj = countries_list[i] as? NSDictionary
                {
                    if let country_name = country_obj["country"] as? String
                    {
                        if let country_code = country_obj["code"] as? String
                        {
                            TableData.append(country_name + " [" + country_code + "]")
                        }
                    }
                }
            }
        }
    }

   do_table_refresh();

}
func do_table_refresh()
{
    self.tableView.reloadData()
}
danielbeard
  • 8,805
  • 3
  • 40
  • 58
Mariyanski
  • 26
  • 1
  • 6

2 Answers2

0

Ok. The exception you are getting is because your tableView is nil after viewdidLoad. It can be a connection problem, so first try this answer: IBOutlet UITableView is null after View did load

Second, if all your nibs and are proper and you are still seeing this error. Then try the below code. [put tableview frame as you want]. This does everything you want to do programmatically and will work.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var TableData:Array< String > = Array < String >()

    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")

        tableView = UITableView(frame: self.view.frame)
        title = "title"
        var menuImage:UIImage = UIImage(named: "sidebtn")!
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "1", style: .Plain, target: self, action: "presentLeftMenuViewController")
        menuImage = menuImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        self.navigationItem.leftBarButtonItem?.image = menuImage
        self.view.addSubView(tableView)


        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return TableData.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = TableData[indexPath.row]
        return cell
    }
    func get_data_from_url(url:String)
    {
        let httpMethod = "GET"
        let timeout = 15
        let url = NSURL(string: url)
        let urlRequest = NSMutableURLRequest(URL: url!,
            cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
            timeoutInterval: 15.0)
        let queue = NSOperationQueue()
        NSURLConnection.sendAsynchronousRequest(
            urlRequest,
            queue: queue,
            completionHandler: {(response: NSURLResponse!,
                data: NSData!,
                error: NSError!) in
                if data.length > 0 && error == nil{
                    let json = NSString(data: data, encoding: NSASCIIStringEncoding)
                    self.extract_json(json!)
                }else if data.length == 0 && error == nil{
                    println("Nothing was downloaded")
                } else if error != nil{
                    println("Error happened = \(error)")
                }
            }
        )
    }
    func extract_json(data:NSString)
    {
        var parseError: NSError?
        let jsonData:NSData? = data.dataUsingEncoding(NSASCIIStringEncoding)!
        let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: &parseError)
        if (parseError == nil)
        {
            if let countries_list = json as? NSArray
            {
                for (var i = 0; i < countries_list.count ; i++ )
                {
                    if let country_obj = countries_list[i] as? NSDictionary
                    {
                        if let country_name = country_obj["country"] as? String
                        {
                            if let country_code = country_obj["code"] as? String
                            {
                                TableData.append(country_name + " [" + country_code + "]")
                            }
                        }
                    }
                }
            }
        }

        do_table_refresh();

    }
    func do_table_refresh()
    {
        self.tableView.reloadData()
    }
}
Community
  • 1
  • 1
  • i have noticed that if i tick a check-box "is initial view controller" in story broad in my "view controller" everything works just fine. However, when che-box is not ticked the debugger shows me the fatal error. By the way, i use code to move between view controllers, instead of segue. the code:"sideMenuViewController?.contentViewController = UINavigationController(rootViewController: GroupListViewController()) sideMenuViewController?.hideMenuViewController()" Maybe this is the reason? – Mariyanski Jul 08 '15 at 20:26
0

In storyboard, find your tableviewcontroller, and right click on the tableview to check the referencing outlets, there are big chances under the referencing outlets, your defined your tableview variable not the same as the one you defined in your codes.

Then you just need to delete the referencing outlets of the tableview, also delete the codes "var tableView: UITableView!", then re-contorl drag the tableview to your code to make a new reference. It happened to me once for this reason.

Pengzhi Zhou
  • 381
  • 5
  • 23