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

问题描述 投票:27回答:3

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

iphone objective-c xcode nib
3个回答
62
投票

#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“,否则您将获得假阴性。

迅速:

guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else {
       ...
    }

(见:touti的原始答案:https://stackoverflow.com/a/55919888/89035


0
投票

我在这里看到两种解决方案。

你可以只调用initWithNibName:bundle:并在失败时捕获异常(我喜欢这个想法,感觉很健壮)。您可能希望验证异常实际上是“找不到文件”异常,而不是例如“内存不足”异常。

或者,您可以使用NSBundle的pathForResource:ofType:来检查是否存在nib,它对于不存在的文件返回nil。


0
投票

解决方案对于swift:

guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else {
   ...
}
© www.soinside.com 2019 - 2024. All rights reserved.