CasualCode
CasualCode

Reputation: 35

Whenever I try to create an Instance of a specific class the whole app crashes (EXC_BAD_ACCESS)

My code seems to crash due to an infinite loop, but I can't find the error. Could someone help me out and look over the code?

Here is my controller:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{
        let location = touch.location(in: self.view)
        let x = Float(location.x)
        let y = Float(location.y)
        let newTouch = Touch(latitude: x,longitude: y)
        TouchService().addTouch(touch: newTouch, grid: _grid)
    }
}

And my model:

import Foundation

class Touch {

    var _lat: Float
    var _long: Float
    var _startingPoint: Touch

    init(latitude lat: Float, longitude long: Float){
        self._lat = lat
        self._long = long
        self._startingPoint = Touch(latitude: lat, longitude: long)
    }
}

I guess there is something wrong with the way I am using the init() function.

Kind regards and thanks in advance, Chris

Upvotes: 0

Views: 44

Answers (2)

Benjamin
Benjamin

Reputation: 1862

Problem

Your initializer creates an infinite loop.

//Touch(latitude: lat, longitude: long) calls the initializer again.
//Since you are inside the initializer, it creates an infinite loop.  
self._startingPoint = Touch(latitude: lat, longitude: long)

Comment that out and you'll see.


Solution

Create a separate class or struct for your values (composition).

class AngularLocation {
    var _lat: Float
    var _long: Float

and

class Touch {
    var destination: AngularLocation
    var startingPoint: AngularLocation

Tweak that to your needs.

Upvotes: 1

dahiya_boy
dahiya_boy

Reputation: 9503

This is how your code is working

class Touch {

var _lat: Float
var _long: Float
var _startingPoint: Touch

init(latitude lat: Float, longitude long: Float){
    self._lat = lat
    self._long = long
    self._startingPoint = Touch(latitude: lat, longitude: long) // It invokes recursively your Touch class with no end, so it causes infinite loop
   }
}

Solution

You have to create different class for StartingPoint.

Upvotes: 0

Related Questions