检查.nib或.xib文件是否存在

rjs*_*ing 28 iphone xcode objective-c nib

在尝试使用initWithNibName:bundle:或类似地加载Nib或Xib文件之前,检查Nib或Xib文件是否存在的最佳方法是什么?

rjs*_*ing 63

#define AssertFileExists(path) NSAssert([[NSFileManager defaultManager] fileExistsAtPath:path], @"Cannot find the file: %@", path)
#define AssertNibExists(file_name_string) AssertFileExists([[NSBundle mainBundle] pathForResource:file_name_string ofType:@"nib"])
Run Code Online (Sandbox Code Playgroud)

下面是一组宏,您可以在尝试加载之前调用它们,.xib或者.nib它们将帮助识别丢失的文件并发出有关错误内容的有用消息.

使用的实际解决方案是:

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

请注意,文档说明ofType:应该是文件的扩展名.但是,即使您使用的是.xib,也需要传递"@"nib",否则您将获得假阴性.

  • 很好的解决方案,但请考虑编辑答案:关于`ofType:`的文档实际上是正确的,并且参数*可以*是文件的扩展名(您实际上可以将整个文件名放在`pathForResource:`中,然后将nil放在`ofType:`,一切都会很好,尽管我不知道这是否是一个好习惯。“ xib” /“ nib”之所以不同是因为* xib文件实际上是经过预处理并在应用程序中打包为nib *,`pathForResource:ofType:`按指定的方式工作;-)(如果您需要检查.app内容,不相信我) (2认同)