gpt4 book ai didi

ios - 正确的 : returning valid data of nil?

转载 作者:行者123 更新时间:2023-11-28 19:11:14 25 4
gpt4 key购买 nike

需要说明:我写了这个类方法来加载图像。如果图像不存在,返回 nil 处理返回值的方式,或者返回未初始化的 UIImage 会更清楚(仍然是 nil 但更清楚)?

+ (UIImage*)loadImageByName:(NSString*)name
{
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [documentsPath stringByAppendingPathComponent:name];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];

if (fileExists){
UIImage* tmpImage = [UIImage imageWithContentsOfFile:imagePath];
return tmpImage;
}
return nil;
}

最佳答案

这很常见。许多 Foundation 和 UIKit 方法都做同样的事情。只需记录一下,如果出错,该方法将返回 nilNSData dataWithContentsofFile: for example .

作为建议,为了防止目录可能发生什么,您可以使用此方法(ref):

- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;

例如:

BOOL isdir;

if ( [[NSFileManager defaultManager] fileExistsAtPath:imagePath isDirectory:&isdir] && (! isdir) )
// file exists and not a directory
else
// handle error like mentioned in another answer

关于ios - 正确的 : returning valid data of nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15297872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com