What's the best way to check if a Nib or Xib file exists before trying to load it using initWithNibName:bundle:
or similar?
views:
876answers:
2
+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
2009-05-28 23:41:23
`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
2009-05-28 23:47:58
initWithNibName:bundle returns nil if nib can't be found; so check for this instead.
Abizern
2009-05-28 23:51:39
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
2009-05-31 13:06:25
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
2009-07-10 23:04:50
Please remove the -[NSBundle autorelease] call from the answer. It will lead to a delayed crash.
nash
2010-01-09 00:13:53