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 开发者_Python百科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?
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]);
}
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]);
精彩评论