正确:返回nil的有效数据?

时间:2013-03-08 15:47:37

标签: ios objective-c

需要澄清:我写了这个类方法来加载图像。如果图像不存在,则返回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;
}

2 个答案:

答案 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方法都是这样做的。只记录错误时该方法返回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