How to avoid crash when something NULL / value comes in variable?

Introduction on NULL Value in Variables causes crashes

API (Application Program Interface) is a set of routines, protocols, and tools for developing mobile applications and other softwares. Basically, an API gives information how application components should communicate. And furter more, APIs are used when programming graphical user interface (GUI) components. Calling API is for data accessing from server and it collects data from server as we call API Function and give require data in appropriate format and it gives back our needed data is some format it may be xml or json or html as per our requirement and server side coding.

Avoid Crash when Null Value Comes

Overview for NULL Value in Variables causes crashes

iOS does not support unwrapping of NULL or values but sometimes due to bad coding or some mistakes NULL comes from server as in response from APIs that we used in our application to get data but due to forced unwraping of NULL iOS app get crashed instantly which can lead to a bad experience to app user. So this type of crash must be avoided.

Solution for NULL Value in Variables avoid crashes

Firstly decide what do you want in your logic that if somthing like NULL comes than what it should exactly do in that case

If you want to creat a function that value that comes from APIs response should be checked and then if NULL comes than in that case it sholud return nil value that iOS can digest and will not give crash in wraping of null.
+ (id)valueOrNil:(id)value {
if ([value isMemberOfClass:[NSNull class]]) {
return nil;
}
return value;
}

yourProperty = [YourClass valueOrNil:[json objectForKey:@"yourKey"]];

Leave a Comment