xcode 检查 .nib 或 .xib 文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/923706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a .nib or .xib file exists
提问by Richard Stelling
What's the best way to check if a Nib or Xib file exists before trying to load it using initWithNibName:bundle:
or similar?
在尝试使用initWithNibName:bundle:
或类似方法加载之前检查 Nib 或 Xib 文件是否存在的最佳方法是什么?
回答by Richard Stelling
Macro
宏
#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"])
Here are a set of macros that you can call before you try an load a .xib
or .nib
, they will help identify missing files and spit out useful message about what exactly is missing.
这里有一组宏,您可以在尝试加载 a.xib
或之前调用.nib
它们,它们将帮助识别丢失的文件并输出有关究竟丢失了什么的有用信息。
Solutions
解决方案
Objective-C:
目标-C:
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.
请注意,文档说明这ofType:
应该是文件的扩展名。但是,即使您使用 .xib,您也需要传递 `@"nib" 否则您将得到假阴性。
Swift:
斯威夫特:
guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else {
...
}
(See: touti's original answer: https://stackoverflow.com/a/55919888/89035)
回答by touti
Solution For swift :
快速解决方案:
guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else {
...
}
回答by Dietrich Epp
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.
你可以只调用 initWithNibName:bundle: 并在它失败时捕获异常(我喜欢这个想法,感觉很强大)。您可能想要验证异常实际上是“未找到文件”异常,而不是“内存不足”异常。
Alternatively, you could check the existence of the nib first, using NSBundle's pathForResource:ofType:, which returns nil for files that don't exist.
或者,您可以首先检查笔尖是否存在,使用 NSBundle 的 pathForResource:ofType:,它为不存在的文件返回 nil。