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

标签 iphone objective-c xcode nib

在尝试使用 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/

相关文章:

objective-c - NSLog 输出中出现换行符

iphone - 仅在 iPad 上出现 "Application windows are expected to have a root view controller at the end of application launch"错误

ios - 在 iPhone 7 的顶部和底部扬声器之间平移声音

ios - 关于使用 PHAuthorizationStatus.authorizationStatus() 的问题

xcode - react native 构建失败 - xcodebuild : error: The workspace named "foo" does not contain a scheme named "foo"

c++ - EXC_BAD_ACCESS 抛出异常

Xcode 5 相当于build设置中的 NS_BLOCK_ASSERTIONS

ios - 触摸开始不射击

iphone - 在UITableViewController中的viewWillAppear之后未调用didDeselectRowAtIndexPath

ios - 嵌套 TableView 给出 UITableViewCellAccessibilityElement 错误