Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS when appending to array class property

I'm new to working with swift and have been converting some ios firebase cordova plugin stuff, but ran into a situation that I don't fully understand regarding arrays. I have two snippets of code, one that works and one that doesn't.

Works

var admobTestDevices: [Any] = []
var randomString: String = "abc123"

@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  func something() {
    admobTestDevices.append(randomString)
  }
}

Doesn't work

@objc(FirebasePlugin)
class FirebasePlugin : CDVPlugin {
  var admobTestDevices: [Any] = []
  var randomString: String = "abc123"

  func something() {
    admobTestDevices.append(randomString)
  }
}

The one that doesn't work produces Thread 1: EXC_BAD_ACCESS (code=1, address=0x8) as an error. Why does one work and the other doesn't? What is the proper way to have a mutable array as a class property?

like image 965
Joshua Avatar asked Nov 17 '25 04:11

Joshua


1 Answers

For some reason collections become immutable in the subclass in some cases.

You could fix this two ways:

1. override init() initialise the array then call super.init

class FirebasePlugin : CDVPlugin {

    var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    override init() {
        admobTestDevices = [Any]()
        super.init()
    }

  func something() {
    admobTestDevices.append(randomString)
  }
}

2. Use the lazy modifier so that the array is initialised when first used.

class FirebasePlugin : CDVPlugin {

    lazy var admobTestDevices: [Any] = []
    var randomString: String = "abc123"

    func something() {
        admobTestDevices.append(randomString)
    }
}
like image 147
David Mayes Avatar answered Nov 18 '25 19:11

David Mayes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!