Я получил ошибку в self.tableView.reloadData(). Может ли это быть из-за того, что я использую библиотеку SSASideMenu, в которой нет переходов между меню и другими представлениями? Мне кажется, что мой tableView не был инициализирован.

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()
}
0
Mariyanski 8 Июл 2015 в 21:44
 – 
Mariyanski
8 Июл 2015 в 21:48

2 ответа

Ok. Исключение, которое вы получаете, связано с тем, что ваш tableView равен нулю после viewdidLoad. Это может быть проблема с подключением, поэтому сначала попробуйте этот ответ: IBOutlet UITableView имеет значение null после загрузки View

Во-вторых, если все ваши перья исправны, и вы все еще видите эту ошибку. Затем попробуйте приведенный ниже код. [поместите рамку таблицы, как хотите]. Это делает все, что вы хотите сделать программно, и будет работать.

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()
    }
}
0
Community 23 Май 2017 в 14:52
Я заметил, что если я отмечаю флажок «является начальным контроллером представления» в широкой истории в моем «контроллере представления», все работает нормально. Однако, когда che-box не отмечен, отладчик показывает мне фатальную ошибку. Кстати, я использую код для перемещения между контроллерами представления вместо перехода. код: "sideMenuViewController?.contentViewController = UINavigationController(rootViewController: GroupListViewController()) sideMenuViewController?.hideMenuViewController()" Может быть, это причина?
 – 
Mariyanski
8 Июл 2015 в 23:26

В раскадровке найдите свой tableviewcontroller и щелкните правой кнопкой мыши на табличном представлении, чтобы проверить ссылочные точки, есть большие шансы на ссылочные точки, определенная вами переменная tableview не совпадает с той, которую вы определили в своих кодах.

Затем вам просто нужно удалить ссылочные точки представления таблицы, а также удалить коды «var tableView: UITableView!», Затем повторно перетащите представление таблицы в свой код, чтобы создать новую ссылку. Это случилось со мной однажды по этой причине.

0
Pengzhi Zhou 9 Дек 2015 в 16:12