简体   繁体   English

UITableView在tableview.datasource开始时崩溃

[英]UITableView crashes at start at tableview.datasource

I have implemented two UITableview in seperate ViewController classes. 我在单独的ViewController类中实现了两个UITableview。 After successfully adding the code for the second UItableView my project builds but stops after loading. 成功添加第二个UItableView的代码后,我的项目构建但在加载后停止。

It stops with a red line on: 它停在一条红线上:

tableView.delegate.dataSource = self

With an error that reads: 出现以下错误:

Thread 1 EXEC_BAD_INSTRUCTION (code-EXC_i386_INVOP,subcode=0x0) 线程1 EXEC_BAD_INSTRUCTION(代码-EXC_i386_INVOP,子代码= 0x0)

AND

fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:在展开Optional值时意外发现nil

Since this didn't happen until adding the second UItableview in the second view controller I'm wondering if maybe my code is conflicting with each other. 由于直到在第二个视图控制器中添加第二个UItableview才发生这种情况,我想知道我的代码是否相互冲突。 I will post copies of both view controllers. 我将发布两个视图控制器的副本。 What should I change? 我应该改变什么?

By the way: FilmsViewController is where the app is crashing. 顺便说一句:FilmsViewController是应用程序崩溃的地方。 Although it was working prior to adding MCViewController Films: 虽然它在添加MCViewController Films之前有效:

B: B:

class FilmsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    weak var tableView : UITableView!
    var FilmArray = [String]()

    let film_url = "https://www.testing.com/api/resources/films/1"
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return FilmArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for:indexPath) as! FilmsAPITableViewCell
        // Configuring Cell
        cell.movieTitle.text = FilmArray[indexPath.row]
        // Returning the cell
        return cell
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        let url:URL = URL(string: film_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY")
        request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization")
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        let paramString = ""

        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }



            var json:Any?

            do
            {
                if let existingData = data {
                    json = try JSONSerialization.jsonObject(with: existingData, options: [])
                }

                //  Prasing JSON
                if let parsedData = json as? [[String:Any]] {
                    for dict in parsedData {
                        if let title = dict["title"] as? String {
                            self.FilmArray.append(title)
                            print(json)
                        }
                    }

                    OperationQueue.main.addOperation({
                        self.tableView.reloadData()
                    })
                }
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }

            if let data_block = server_response["data"] as? NSDictionary
            {
                if let session_data = data_block["session"] as? String
                {
                    //  self.login_session = session_data

                    let preferences = UserDefaults.standard
                    preferences.set(session_data, forKey: "session")

                    //  DispatchQueue.main.async(execute: self.LoginDone)
                }
            }
        })

        task.resume()

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

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



}

MC: MC:

   class MCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let message_url = "https://www.testing.com/api/resources/get_film_message/film_id/3825"
    let send_url = "https://www.testing.com/api/resources/send_film_message"
    let film_id = "3825"
    var messageArray = [String]()
    weak var tableView : UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messageArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "msgContent", for:indexPath) as! MessageTableViewCell
        // Configuring Cell
        cell.msgContent.text = messageArray[indexPath.row]
        // Returning the cell
        return cell
    }



    @IBOutlet weak var MessageInput: UITextField!
    @IBAction func Sendmsg(_ sender: Any) {
        Sendmsg(username:MessageInput.text!, password: film_id)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        // Do any additional setup after loading the view.
        //let post_data: NSDictionary = NSMutableDictionary()


        //        post_data.setValue(username, forKey: "username")
        //        post_data.setValue(password, forKey: "password")

        let url:URL = URL(string: message_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY")
        request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization")
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
        // Do any additional setup after loading the view.
        var paramString = ""


        //        for (key, value) in post_data
        //        {
        //            paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
        //        }
        //
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }



            let json: Any?

            do
            {
                json = try JSONSerialization.jsonObject(with: data!, options: [])
                if let parsedData = json as? [[String:Any]] {
                    for dict in parsedData {
                        if let title = dict["message"] as? String {
                            self.messageArray.append(title)
                            print(json)
                        }
                    }
                }
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }


            if let data_block = server_response["data"] as? NSDictionary
            {
                if let session_data = data_block["session"] as? String
                {
                    //  self.login_session = session_data

                    let preferences = UserDefaults.standard
                    preferences.set(session_data, forKey: "session")

                    //  DispatchQueue.main.async(execute: self.LoginDone)
                }
            }



        })

        task.resume()
    }

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

    func Sendmsg(username:String, password:String)
    {
        let post_data: NSDictionary = NSMutableDictionary()


        post_data.setValue(username, forKey: "message")
        post_data.setValue(password, forKey: "film_id")

        let url:URL = URL(string: send_url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("740c94c51891c02b64d6c78840b478fe0b02fe2c", forHTTPHeaderField: "X-API-KEY")
        request.setValue("Basic YmhlZW0uZW5nckBnbWFpbC5jb206YmgzM20=", forHTTPHeaderField: "Authorization")
        request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

        var paramString = ""


        for (key, value) in post_data
        {
            paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
        }

        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest, completionHandler: {
            (
            data, response, error) in

            guard let _:Data = data, let _:URLResponse = response  , error == nil else {

                return
            }



            let json: Any?

            do
            {
                json = try JSONSerialization.jsonObject(with: data!, options: [])
                print(json)
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }


//            if let data_block = server_response["data"] as? NSDictionary
//            {
//                if let session_data = data_block["session"] as? String
//                {
//                    self.login_session = session_data
//                    
//                    let preferences = UserDefaults.standard
//                    preferences.set(session_data, forKey: "session")
//                    
//                    DispatchQueue.main.async(execute: self.LoginDone)
//                }
//            }
//            


        })

        task.resume()


    }


    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}

Where are you initializing tableView ? 你在哪里初始化tableView Seems like it might be nil .... 好像它可能是nil ......

tableView = UITableView(frame: frame)

If you're using storyboard/xib, you can also hook tableView up as an IBOutlet . 如果您正在使用storyboard / xib,您还可以将tableView作为IBOutlet挂钩。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 tableView.datasource =自身错误:无法识别的选择器 - tableView.datasource = self error:unrecognized selector tableView.cellForRow(at :)和tableView.dataSource?tableView(tableView:cellForRowAt :)之间的区别 - Difference between tableView.cellForRow(at:) and tableView.dataSource?tableView(tableView:cellForRowAt:) UITableView dataSource必须从tableView:cellForRowAtIndexPath返回单元格 - UITableView dataSource must return cell from tableView:cellForRowAtIndexPath 原因:“ UITableView数据源必须从tableView:cellForRowAtIndexPath返回单元格 - reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath UITableView数据源必须从tableView:cellForRowAtIndexPath错误返回单元格 - UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath eror UITableView数据源必须从tableView:cellForRowAtIndexPath:返回一个单元格: - UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:? UITableView中的节数得到更新,但tableview数据源数组未更新 - Number of sections in UITableView gets updated but not the tableview datasource array Swift UITableView删除行项目-tableview数据源是核心数据 - Swift UITableView delete row item - tableview datasource is Core Data iOS:UITableView数据源必须从tableView:cellForRowAtIndexPath返回一个单元格: - iOS: UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath: UITableView数据源必须从tableView:cellForRowAtIndexPath返回单元格” - UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM