1

I have a String property as part of a custom object. When I try to access the String on the custom object (when it's Null), the program crashes.

I can tell that the string is of type NSNull by printing out the custom object.

Every time I try

if theString == nil if theString == NSNull() if theString.isEmpty

the program crashes with [NSNull length]: unrecognized selector sent to instance

What I don't understand is where it's trying to call length. I would imagine it only calls length on the isEmpty function, but it crashes on the other two conditionals as well.

I'm thinking it could be because the custom object is created in objective-c with an NSString, but this also crashes when I try to convert the String to an NSString, so I'm not sure how to go about it.

Thanks!

cph2117
  • 2,651
  • 1
  • 28
  • 41
  • 2
    I think the underlying error is that the pointer to `NSString` is set to `NSNull` in Objective-C. `NSNull` should only be used to add empty values to collections like arrays or dictionaries. For plain object pointers you should use `nil` instead which will get translated to Objective-C as expected. – hennes Sep 02 '15 at 18:53
  • Right you are! Thanks! I figured it might be something like that, but why do Swift and Obj-C interpret NSNull differently? – cph2117 Sep 02 '15 at 18:58
  • 1
    They don't. Obj-c is dynamically typed. This means you can assign NSNull to a string if you want, but if you try to call a method on that string, you should end up with 'unknown selector' You really shouldn't set an NSString to NSNull. Oh and it probably tries to call length because then implementation of equals for strings checks lengths. – sylvanaar Sep 02 '15 at 19:38

1 Answers1

3

I don't like answering my own questions, but for what it's worth, if an Obj-C property is NSNull and you attempt to unwrap it in Swift, it will give you an error.

I fixed this by doing a check on my custom object (in Obj-C model), and if a property is NSNull then you set that property equal to nil like so:

if (theString == (id)[NSNull null]){
     theString = nil

}
cph2117
  • 2,651
  • 1
  • 28
  • 41