Swift BAD ACCESS Code = 2

时间:2016-06-01 17:32:36

标签: ios swift charts exc-bad-access

我正在尝试创建一个应用程序,在AppleTV电视的2/3视图中显示来自纽约时报政治部分的标题,并在另一个1/3视图的饼图上方显示折线图。我写了两个单独的程序,一个显示标题,一个显示图表,但是当试图将它们组合起来时,我遇到了这个错误

  

“BAD ACCESS”

在线。

pieChartView!.holeColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
pieChartView!.descriptionText = ""

任何见解都将不胜感激,谢谢!

import UIKit
import Charts

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var table: UITableView!
    @IBOutlet weak var pieChartView: PieChartView?
    @IBOutlet weak var lineChartView: LineChartView?

    let baseURL = "http://api.nytimes.com/svc/topstories/v1/politics.json?api-key=dd56f74b26c444f497b4588fd2944146"
    var headlines = [String]()
    var bernieSanders = [String]()
    var hillaryClinton = [String]()
    var donaldTrump = [String]()

    var bernieCount: Double = 0.0
    var hillaryCount: Double = 0.0
    var donaldCount: Double = 0.0
    var headlineCount = [Double]()

    override func viewDidLoad() {

        super.viewDidLoad()

        let candidates = ["Sanders", "Clinton", "Trump"]
        self.getJSON()
        sleep(2)
        setChart(candidates,  values: headlineCount)
        sleep(2)
        self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

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

    func getJSON() {

        let url = NSURL(string: baseURL)
        let request = NSURLRequest(URL: url!)
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in

            if error == nil {
                let SwiftyJSON = JSON(data: data!)
                let theTitle = SwiftyJSON["results"].arrayValue

                for title in theTitle {
                    let titles = title["title"].stringValue
                    self.headlines.append(titles)

                }

                for headline in self.headlines {
                    if headline.lowercaseString.rangeOfString("sanders") != nil {
                        self.bernieSanders.append(headline)
                    }
                    if headline.lowercaseString.rangeOfString("clinton") != nil {
                        self.hillaryClinton.append(headline)
                    }
                    if headline.lowercaseString.rangeOfString("trump") != nil {
                        self.donaldTrump.append(headline)
                    }
                }

                self.bernieCount = Double(self.bernieSanders.count)
                self.hillaryCount = Double(self.hillaryClinton.count)
                self.donaldCount = Double(self.donaldTrump.count)

                self.headlineCount.append(self.bernieCount)
                self.headlineCount.append(self.hillaryCount)
                self.headlineCount.append(self.donaldCount)

                print("Number Of Headlines That Mention Each Candidate")
                print("Bernie:  \(self.bernieCount)")
                print("Hillary: \(self.hillaryCount)")
                print("Donald:  \(self.donaldCount)\n")
                print(self.headlines)
            }
            else {
                print("there was an error")
            }
        }
        task.resume()
    }



    // From the UITAbleViewDataSource
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return headlines.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
        cell.textLabel!.text = self.headlines[indexPath.row]
        cell.textLabel!.font = UIFont(name:"Avenir", size:25)
        return cell
    }
    // From the UITableViewDelegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped on cell # \(indexPath.row)")
    }

    func setChart(dataPoints: [String], values: [Double]) {

        var dataEntries: [ChartDataEntry] = []

        for i in 0..<dataPoints.count {
            let dataEntry = ChartDataEntry(value: (values[i]), xIndex: i)
            dataEntries.append(dataEntry)
        }

        let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "")
        let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
        pieChartView!.backgroundColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
        pieChartView!.holeColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
        pieChartView!.descriptionText = ""
        pieChartView!.data = pieChartData

        let blue = UIColor(hue: 0.6194, saturation: 1, brightness: 0.89, alpha: 1.0)
        let lightblue = UIColor(hue: 0.5222, saturation: 1, brightness: 0.92, alpha: 1.0)
        let red = UIColor(hue: 0, saturation: 1, brightness: 0.86, alpha: 1.0)
        let colors: [UIColor] = [blue, lightblue, red]

        //        for _ in 0..<dataPoints.count {
        //            let red = Double(arc4random_uniform(256))
        //            let green = Double(arc4random_uniform(256))
        //            let blue = Double(arc4random_uniform(256))
        //
        //            let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
        //            colors.append(color)
        //        }
        //
        pieChartDataSet.colors = colors


        let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "NY Times Headlines")
        let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
        lineChartDataSet.colors = [NSUIColor(hue: 0.3194, saturation: 1, brightness: 0.66, alpha: 1.0)]
        lineChartDataSet.circleColors = [NSUIColor(hue: 0.3194, saturation: 1, brightness: 0.66, alpha: 1.0)]
        lineChartView!.backgroundColor = UIColor(hue: 0.0111, saturation: 0.15, brightness: 1, alpha: 1.0)
        lineChartView!.descriptionText = ""
        lineChartView!.xAxis.labelPosition = .Bottom
        lineChartView!.data = lineChartData

    }

}

2 个答案:

答案 0 :(得分:0)

正如@vadian建议的那样,我需要相应地设置自定义视图的类。

答案 1 :(得分:0)

对于那些也可能出现这个神秘错误的人:我的问题是我更改了一个插座的类,但忘记在Storyboard-View中更改它。在正确声明视图和插座后,错误消失了。

enter image description here

enter image description here