Почему я получаю конфликт определения tableView?

Я прохожу курс программирования iOS через udemy и пытаюсь использовать функции UITableViewDelegate для определения и заполнения таблицы.

Я получаю сообщение об ошибке «Определение конфликтует с предыдущим значением» при вызове cellForRowAtIndexPath, и это относится к numberOfRowsInSection.

Я использую версию 6.1.1 (6A2008a)

Есть идеи?

import UIKit

class ViewController: UIViewController, UITableViewDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

//let's go ahead and define the URL that we are going to use. this literrally is saying, create a URL that Xcode can use using the string below.
    let url0 = NSURL(string: "http://www.weather-forecast.com")

    //let's create a task. the task will go to weather-forecast.com and get the contents.
    //first, we define the task, and then specify the method that is associated with that task.

    //we need to create an array of string values for the cities we are looking for that will be used in the task, as well as outside of the task.
    var arrayCities: [String] = []

    let task0 = NSURLSession.sharedSession().dataTaskWithURL(url0!) {
        //NSURLSession opens an http session inside of the app.
        //.dataTaskWithURL gets the data from the URL
        //.dataTaskWithURL responds with three variables: data, response, error
        (data, response, error) in
        if error == nil {

            //if error is nil, create a variable urlContent with type NSSTring, and encode data with NSUTF8StringEncoding
            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)

            //let's then set up a sting that we can parse correctly
            var stringParse = NSString(string: urlContent!)


            //let's start parsing urlContent and putting it into an array for us to put into a table.



            //let's see if the desired list of cities are indeed inside of the urlContent
                if urlContent?.rangeOfString(">Paris Weather Forecast<") != nil{
                    arrayCities.append("Paris")
                }
                    else{println("paris has not been added")}

                if urlContent?.rangeOfString(">New York Weather Forecast<") != nil{
                    arrayCities.append("New York")
                }
                    else {println("New York has not been added")}

                if urlContent?.rangeOfString(">Dubai Weather Forecast<") != nil{
                    arrayCities.append("Dubai")
                }
                    else {println("Dubai has not been added")}

                if urlContent?.rangeOfString(">Rome Weather Forecast<") != nil{
                    arrayCities.append("Rome")
                }
                    else {println("Rome has not been added")}

                if urlContent?.rangeOfString(">Mumbai Weather Forecast<") != nil{
                    arrayCities.append("Mumbai")
                }
                    else {println("Mumbai has not been added")}


                if urlContent?.rangeOfString(">London Weather Forecast<") != nil{
                arrayCities.append("London")
                }
                    else {println("London has not been added")}


                if urlContent?.rangeOfString(">Berlin Weather Forecast<") != nil{
                    arrayCities.append("Berlin")
                }
                    else {println("Berlin has not been added")}

            //println(stringParse)
            //println(urlContent)
            println(arrayCities)

            println(arrayCities.count)}
            }
    //make sure we kick off task0.
    //we do this by calling the resume() method
    task0.resume()

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

    //the below code will be run eveytime for every amount of rows in the table.
    //the mehtod defines the contents of each individual cell. you can put images and looks of the cells. it returns a UITable view cell, and all the content that goes with it.
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //the variable indexPath tells you what row you are in everytime.

        //let's create a cell to return. the reuseIdentifier is used to create a reference name for the cell.
        //when we create and edit a prototype cell, we are referencing all the cell styles.
        //if we had a situation where we had active users that appeared red in the table and active users that appeared green, we would need to set up two seperate Prototpye cells and two reuseIdentifiers.
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        cell.textLabel?.text = arrayCities[indexPath.row]
        return cell

    }



}


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


}

person scottyoshimura    schedule 20.03.2015    source источник


Ответы (1)


Пожалуйста, вставьте свою ошибку в журнал, если ни одно из двух приведенных ниже предложений не помогло.

Идентификатор ячейки

В представлении ViewController (раскадровке) убедитесь, что у вас есть ячейка-прототип. Выберите его и получите доступ к его атрибутам. Убедитесь, что cell identifier совпадает с тем, что вы используете здесь: let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

cellIdentifier

Обновить данные

После того, как вы получили данные, вы можете перезагрузить табличное представление:

self.tableView.reloadData()
person lchamp    schedule 20.03.2015
comment
Спасибо, что ответили мне Ichamp. Я уже сделал прототип ячейки и правильный reuseIdentifier. У меня не было self.tableView.reloadData(). У меня все еще были некоторые проблемы, и я нашел кого-то еще с похожей проблемой [здесь] (stackoverflow.com/questions/24484493/). Скачал последнюю версию x-code 6.2, выключил на ночь, перезагрузил, и сегодня ошибка ушла. Сейчас работаем над другими ошибками. Спасибо еще раз. - person scottyoshimura; 23.03.2015
comment
Если ответ помог (я не уверен, что это было так, если вы только что обновили Xcode), отметьте его как принятый. - person lchamp; 24.03.2015