1

Isn't NSValue an NSObject ? So why am I crashing on

    var coordinatesRawData = NSValue(MKCoordinate: coordinates.first!)
    if coordinatesRawData != nil {
        // Crashing here. I have a valid NSValue object
        aCoder.encodeObject(coordinatesRawData, forKey: "coordinatesRawData")
    }

Error Log

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs'

But if I do this

    var coordinatesRawData = NSValue()
    aCoder.encodeObject(coordinatesRawData, forKey: "coordinatesRawData")

There is no crash - Both are NSValues .. right ?

Note, all my other NSCoding / Decoding is working fine.

DogCoffee
  • 19,820
  • 10
  • 87
  • 120
  • I believe this is because the keyed archiver can not get keys for the struct entries. An alternative is you use NSArchiver which may work for you, at the expense of less flexibility. Or don't use a struct and store separate fields or create your own object which supports NSCoding. – Rory McKinnel Jun 18 '15 at 23:20
  • I assumed NSValue was like a Wrapper, I could throw in this Struct and be golden. Guess not, I have a working work around but this would have been cleaner. – DogCoffee Jun 18 '15 at 23:22
  • 1
    It looks to me like NSValue(MKCoordinate:) is broken. You should file a bug report on this. – matt Jun 18 '15 at 23:28
  • This is the 2nd bug I've found in a short period of time. http://stackoverflow.com/questions/30158193/ios-parse-pfobject-subclassing-with-swift-behaviour I agree it has to be a bug. – DogCoffee Jun 18 '15 at 23:34

1 Answers1

1

I didn't even get as far as you did. I crashed on just these two lines:

let loc = CLLocationCoordinate2D(latitude: 20, longitude: 20)
let val = NSValue(MKCoordinate:loc)

This tells me that NSValue(MKCoordinate:) is broken. And it's not a Swift issue; I get the same crash using the same code translated into Objective-C.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • If I were, we wouldn't compile, would we? – matt Jun 18 '15 at 23:45
  • I just put it into my viewDidLoad and runs, giving the the NSValue of <00000000 00003440 00000000 00003440> .... weirdness :-) – DogCoffee Jun 18 '15 at 23:48
  • Yup, I saw that too on a different run. – matt Jun 18 '15 at 23:49
  • That `<00000000 00003440 00000000 00003440>` is the `loc`. This tells you that we are not getting an NSValue object - we are just getting the original struct. And that explains _your_ crash. NSValue is failing to wrap the struct like it's supposed to. – matt Jun 19 '15 at 00:12
  • I just tried this in iOS 9. We still crash with `NSValue(MKCoordinate:CLLocationCoordinate2DMake(1,2))`. I'm filing a bug too. – matt Jun 19 '15 at 14:58