在尝试使用 initWithNibName:bundle:
或类似方法加载之前检查 Nib 或 Xib 文件是否存在的最佳方法是什么?
最佳答案
宏观
#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"])
这是一组宏,您可以在尝试加载 .xib
或 .nib
之前调用它们,它们将帮助识别丢失的文件并吐出有用的消息关于究竟缺少什么。
解决方案
Objective-C :
if([[NSBundle mainBundle] pathForResource:fileName ofType:@"nib"] != nil)
{
//file found
...
}
请注意,文档指出 ofType:
应该是文件的扩展名。然而,即使您使用的是 .xib,您也需要传递 `@"nib",否则您将得到假阴性结果。
swift :
guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else {
...
}
(参见:touti 的原始答案:https://stackoverflow.com/a/55919888/89035)
关于iphone - 检查 .nib 或 .xib 文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/923706/