在 Objective-C 中的 NSDocument 中存储许多图像:[iOS]

Storing Many Images in NSDocument in Objective-C : [iOS]

我正在尝试在 NSDocument 中存储许多图像,名称模式如下:-

image 1, image 2, image 3, image 4, .....

图像计数应随着点击注册按钮的次数而增加。为了存储这个按钮的点击次数,我使用的是 NSUserDefault。但问题是在应用程序崩溃后我只能存储 1 张图像。

以下是我使用的代码:-

- (IBAction)registerFaceAction:(id)sender
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];

    long count = [userDefaults integerForKey:@"my_key"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:count];

    NSMutableString *imageName = [NSMutableString string];

    [imageName appendString:[NSString stringWithFormat:@"ImageData %ld", count]];

    [imageName appendString:[NSString stringWithFormat: @".png"]];

    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];

    UIImage *image = _inputImage;

    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO];

    [userDefaults setInteger:count+1 forKey:@"my_key"];

    [userDefaults synchronize];        

}

您准备的 documentsDirectory 字符串不正确。它不应该随着计数而改变。

更正以下代码:

- (IBAction)registerFaceAction:(id)sender
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];

    long count = [userDefaults integerForKey:@"my_key"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];//corrected line

    NSMutableString *imageName = [NSMutableString string];

    [imageName appendString:[NSString stringWithFormat:@"ImageData %ld", count]];

    [imageName appendString:[NSString stringWithFormat: @".png"]];

    NSLog(@"imageName is :- %@",imageName);

    NSLog(@"Count is :- %ld",count);

    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imageName];

    UIImage *image = self.imgCapture;

    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:savedImagePath atomically:NO];

    [userDefaults setInteger:count+1 forKey:@"my_key"];

    [userDefaults synchronize];

    NSLog(@"imageName is :- %ld",count);

}

Count 应该是 0 始终获取文档目录路径。 第一次用户默认 returns 0,因此它获取文档目录,但在第一个之后计数变为 1,并且当它尝试从 1 索引形式 paths 数组中查找对象时给出数组越界异常。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

编码愉快...