CodeGuy
CodeGuy

Reputation: 28905

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?

Upvotes: 0

Views: 1238

Answers (2)

Caleb
Caleb

Reputation: 125007

What do you mean by "print out contents of objects"? If you're dereferencing a nil pointer, that'll cause a problem. If you're just printing the pointer, that should be OK. You can also send messages to nil without problem, so you could do this:

NSLog(@"theObject is: %@", [theObject description]);

Upvotes: 1

Mr. Berna
Mr. Berna

Reputation: 10645

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]);
}

Upvotes: 1

Related Questions