views:

876

answers:

2

What's the best way to check if a Nib or Xib file exists before trying to load it using initWithNibName:bundle: or similar?

+1  A: 

There are two solutions I see here.

You could just call initWithNibName:bundle: and catch an exception if it fails (I like this idea, it feels robust). You will probably want to verify that the exception is in fact a "file not found" exception rather than, say, an "out of memory" exception.

Alternatively, you could check the existence of the nib first, using NSBundle's pathForResource:ofType:, which returns nil for files that don't exist.

Dietrich Epp
`initWithNibName:bundle:` doesn't throw an exception if the file does not exist you only get problems when you try to use it with something like `pushViewController:animated:`
rjstelling
initWithNibName:bundle returns nil if nib can't be found; so check for this instead.
Abizern
A: 

The actual solution used was:

if([[NSBundle mainBundle] pathForResource:fileName ofType:@"nib"] != nil) 
{
//file found
...
}

Please note, the documentation states that ofType: should be the extension of the file. However even if you are using .xib you need to pass `@"nib" or you will get a false-negative.

rjstelling
Is autorelease really needed in this call?
LucasTizma
No, you should *not* autorelease the return value of [NSBundle mainBundle] as you do not own the result (see the Cocoa Memory Management Programming Guide).
Barry Wark
Please remove the -[NSBundle autorelease] call from the answer. It will lead to a delayed crash.
nash