简体   繁体   中英

UITableView = nil, fatal error : unexpectedly found nil while unwrapping an Optional value

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()
}

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()
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM