-2

I am fetching data from the model in this way

if let birthdate = personInfo?.str_Birthdate {
    cell.dobTF.text = birthdate
}

But app crash and return this error

'-[NSNull length]: unrecognized selector sent to instance 0x10f8c6fc0'

Vivek Molkar
  • 3,910
  • 1
  • 34
  • 46
Shahbaz Akram
  • 1,598
  • 3
  • 28
  • 45

1 Answers1

0

What you are getting here is NSNull. It is an object representing null in context of objective-C arrays and dictionaries. Specifically in JSONs it distinguishes between receiving field (null) instead of not receiving a field at all. In your case I assume this value is force-unwrapped as a string so the error is a bit late. Please try the following:

if let dateObject = personInfo?.str_Birthdate {
    if let nullObject = dateObject as? NSNull {
        // A field was returned but is (null)
    } else if let stringObject = dateObject as? String {
        cell.dobTF.text = stringObject
    } else {
        // Unknown object
    }
} else {
    // This field is missing
}

You can actually just convert all NSNull instances to nil using something like:

func removeNSNullInstancesFrom(_ item: Any?) -> Any? {
    guard let item = item else { return nil }
    if let _ = item as? NSNull {
        return nil
    } else if let array = item as? [Any] {
        return array.compactMap { removeNSNullInstancesFrom($0) }
    } else if let dictionary = item as? [String: Any] {
        var newDict: [String: Any] = [String: Any]()
        dictionary.forEach { item in
            guard let value = removeNSNullInstancesFrom(item.value) else { return }
            newDict[item.key] = value
        }
        return newDict
    } else {
        return item
    }
}

You can use this on the whole response object or a specific item. In your case you can do: cell.dobTF.text = removeNSNullInstancesFrom(birthdate).

But this method should in general recursively remove all NSNull instances from fields, arrays and dictionaries which are standard for JSON.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43