Search code examples
iosxcodenslog

How to print something so that if it is nil, it will print nil - iOS


I always use NSLog to print out contents of objects when I am debugging my iOS applications. But any time I come across a "nil" object, the program crashes. In Java, if an object is null, it will print "null". Is there a way to do this in Objective-C?


Solution

  • Something like:

    if (questionableObject == nil)  {
       NSLog(@"questionableObject is nil.");
    } else {
       NSLog(@"questionableObject is: %@", questionableObject);
    }
    

    I've only really run into this problem when I send a message to an object inside the NSLog parameter list that uses a nil object as a parameter. Something like this:

    if (questionableObject == nil)  {
       NSLog(@"questionableObject is nil.");
    } else {
       NSLog(@"result is: %@", [something someMessage:questionableObject]);
    }