限制文档文件夹中保存的图像数量

时间:2013-02-10 12:04:57

标签: iphone

我想拍摄3张图片并将其作为IMAGE_1,IMAGE_2和IMAGE_3保存在文档文件夹中。我想将图像数量限制为仅三个图像,这意味着第四个图像将被保存为新的“IMAGE_1”替换第一个图像(旧的IMAGE_1),第五个图像将变为“IMAGE_2”,依此类推。以下代码会将图像保存为IMAGE_1,IMAGE_2,IMAGE_3,IMAGE_4,...我应该如何限制保存的图像数量?

- (void) saveImage:(UIImage*)image 
{
    NSData *imageData =
    [NSData dataWithData:UIImageJPEGRepresentation(image, 0.9f)];
    [imageData writeToFile:[self savePath] atomically:YES];
}

- (NSString*) savePath
{
    int i=1;
    NSString *path;
    do {
    path = [NSString stringWithFormat: @"%@/Documents/IMAGE_%d.jpg", NSHomeDirectory(), i++];
} while ([[NSFileManager defaultManager] fileExistsAtPath:path]); 

    return path;
}

1 个答案:

答案 0 :(得分:1)

static int i=1;  // Place it below your @implementation yourclassname

- (void) saveImage:(UIImage*)image {
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.9f)];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *path = [self savePath];

    if([fileMgr fileExistsAtPath:path])
        [fileMgr removeItemAtPath:path error:NULL];
    [imageData writeToFile:path atomically:YES];
}
- (NSString*) savePath {
    if(i==4)
        i=1;
    return [NSString stringWithFormat: @"%@/Documents/IMAGE_%d.jpg", NSHomeDirectory(), i++];
}

希望它有所帮助。