shubham mishra shubham mishra - 1 year ago 107
Objective-C Question

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

I am trying to store many images in NSDocument with the name pattern like :-

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

Image count should increase with number of times a register button is tapped. And for storing this button tapped count i am using NSUserDefault. But the problem is that i am only able to store 1 image after that the application is crashing.

Following is the code i am using :-

- (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];


Answer Source

Count should be 0 always to get the document directory path. For the first time the user default returns 0, hence it gets the document directory, but after the first one the count becomes 1, and when it tries to find the object from 1 index form paths array it gives array out of bound exception.

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

NSString *documentsDirectory = [paths objectAtIndex:0];

Happy coding...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download