Pretty much everyone that writes about the UISplitView on the iPad uses the following code structure to dismiss a popover:
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES];
}
I though Objective-C was happy to ignore messages that are passed to nil? In fact, in the File > New Project > New Split View Application template, there’s an example of this shortcut in the same code block (DetailsViewController.m):
- (void)setDetailItem:(id)newDetailItem {
if (detailItem != newDetailItem) {
[detailItem release]; //might be nil
detailItem = [newDetailItem retain];
// Update the view.
[self configureView];
}
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES]; //was checked for nil
}
}
Why is that second if necessary?
In this case, it’s not important and just adds a line of code.
However, when the return type of a method is not an integral type, this check can be important. Oh crap, it seems they fixed that in ObjC 2.0.It’s important to check for
nilwhen a non-scalar type should be returned. Take this example:In this example, our
cis happily memset to have-1s in every field (except for the double, which I don’t quite know what it does). Messagingnilindeed resets everything to zero.But wait!
Just suppose we change our
maina little bit:It now happens that
cwill hold what[[[Foo alloc] init] complex]returned, even though the return value was technically not used. (EDIT Compiled fromgcc -lobjc -framework Cocoaas an x86_64 binary. Your mileage may vary with your architecture.)It seems the return value of a big
structwhen messagingnilis undefined.