Search code examples
xcodeclasscore-plotfatal-erroriboutlet

Assigning the Outlet from Different Class? (Core Plot)


I have a class which is for bluetooth data receiving and I wonder to send the receiving data to class UIViewController and do the realtime plotting (CorePlot)

class BluetoothManager: NSObject {
   func dataReceiving(value: [Int]){
      MainController().plot(dataOne: [Int], dataTwo: [Int])
}

MainController class:

class MainController: UIViewController,CPTScatterPlotDataSource {

    @IBOutlet weak var graphView: CPTGraphHostingView!

    func plot(dataOne: [Int], dataTwo: [Int]){
        let newGraph = CPTXYGraph(frame: CGRectZero)
        graphView.hostedGraph = newGraph
    }
}

When the procedure goes to graphView.hostedGraph = newGraph , there will have a fatal error:

unexpectedly found nil while unwrapping an Optional value

Can anybody tell me how to exactly solve this problem? I know maybe the error happened because I create the new instance of MainController but I'm very new to iOS development, so I really need to know the detailed procedure to fix it... BIG Thanks!!!!!!! I'll be very appreciative

I upload my project here: https://www.dropbox.com/sh/xyghqhyxyy9lm1f/AACfV8JUj7C2Lo3MNcOiGfnIa?dl=0 Could you guys help me to solve this problem? I really need to know......


Solution

  • The graphView outlet is being released early because of the weak reference. Declare it like this:

    @IBOutlet var graphView: CPTGraphHostingView!
    

    Edit:

    I just noticed another problem. The line MainController().plot(dataOne: [Int], dataTwo: [Int]) creates a new MainController object, which doesn't have a reference to the graph view. You need to obtain a reference to the existing view controller and call the plot function on it.