需要澄清:我写了这个类方法来加载图像。如果图像不存在,则返回nil
处理返回值的方式,还是更清楚地返回未初始化的UIImage
(仍然是零但更清晰)?
+ (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;
}
答案 0 :(得分:2)
返回nil,这是指示操作无法完成的正确方法... 那么下面的代码就可以了:
UIImage * someImage;
if ((someImage = [YourClass loadImageByName:@"donkey"]))
{
//do something
}else{
//failure
}
如果您愿意,也可以包含某种反馈
+ (UIImage*)loadImageByName:(NSString*)name error:(NSError **)err
{
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;
}else{
if(err)
{
*err = [NSError someErrorMethodHere...];
}
}
return nil;
}
答案 1 :(得分:2)
很常见。许多Foundation和UIKit方法都是这样做的。只记录错误时该方法返回nil
。 NSData 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