Tagged: code snippet

Xcode Code Snippets

Xcode appreciation is not universal. @wtfxcode, for example, is a Twitter account relating various issues (and/or frustrations). Also, I often see threads of discussions between developers on how JetBrain’s AppCode is so much superior.

For my part, I never felt the need to switch to a new IDE. Albeit not perfect (no software/IDE is), Xcode fits my needs well.

Having said that, this post is about a bug I encountered in Xcode.

Xcode has a built-in code snippets library in the Utilities bar. (And you can add your own snippets too. See this very useful answer on stackoverflow.com). I use it mainly for Core Data fetch requests. Drag and drop, and press tab to replace parameters for your own variables.

One time I got compiling errors over this (completed) code snippet:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"<#Entity name#>" inManagedObjectContext:<#context#>];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [<#context#> executeFetchRequest:fetchRequest error:&error];             // compiling error at this line
if (fetchedObjects == nil) {
<#Error handling code#>                  // compiling error at this line
[fetchRequest release];

I stared at my code for a while, making sure that the few code I did input in there was correct, and indeed it was. I couldn’t get where the error could have come from. I tried to manually re-type the same code. The errors were gone.


checking NSError for nil

We’ve all seen this code:

NSError *error;
// do something...
if (error) { // act on error if any, but crashing instead... }

There should be nothing wrong with this code snippet. Except that there can be. I’ve countered many occasions where error was not initialized to nil by default, the if statement was evaluated to true and associated code was executed. But since there was no error, I got runtime errors, many of which were EXC_BAD_ACCESS…

Changing to:

NSError *error = nil;

made my code run fine.

In the literature I’ve read, all variables in Objective-C are initialized to nil, even if not done explicitly. This seems to be not true anymore. Does anyone have an answer to that? Please share in the comments if you do. My theory is because of the new LLVM compiler, but please prove me wrong if I am.