So, I'm following the iOS-Charts tutorial on AppCoda, I followed it perfectly, then when I was having issues I also copied the code to match their exactly.
The problem is, when I try and create a pie chart, then run it. I get the error:
Thread1: EXC_BAD_ACCESS (code=2, address=0x2a0c220)
and the app crashes. When it crashes, it highlights this line:
pieChartView.data = pieChartData
Here is as screen shot of the screen:
Here is the full code from the viewcontroller.swift:
import UIKit
import Charts
class ViewController: UIViewController {
@IBOutlet weak var pieChartView: PieChartView!
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: "Units Sold")
let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
pieChartView.data = pieChartData
var colors: [UIColor] = []
for i 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
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]
setChart(months, values: unitsSold)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
It looks you might have missed this part:
Next drag a View onto the Bar Chart View Controller and pin its edges as shown. This View is a child of the main View in the controller.
You need to create a UIView in your View Controller and link this to the @IBOutlet weak var pieChartView: PieChartView! in your code.
Then it will work. And it looks like a nice library.
Hope it helps. Please let us know.
EDIT:
Go to your View Controller on the storyboard and drag a UIView. Then select UIView and set its class as PieChartView in identity inspector. Open the ViewController swift file and right click on the little circle on the @IBOutlet line at the top and drag it on to the UIView that you just created by holding the right click and leave it. Now you connected outlet to the code and it will recognize the pieChartView var as an object instead nil which currently is.