Search code examples
iosarraysmemorywarningsnsdata

Memory warning when saving to NSData Array


I'm building an application that allows the user to take several pictures in a row with the device camera.

Every time a picture is taken, it is sent to an array as an NSData variable. The problem is: when the array gets like 30 pictures, it starts to create memory warnings and eventually crashes the application.

When I leave that view I save that array to NSUserDefaults, which can also lead to memory warnings and crashing.

I need to be able to save information of like 200 taken pictures. How can I achieve this without memory warnings?

Btw: I'm using the Apple's SquareCam sample code to take pictures with the camera.

Thanks in advance.


Solution

  • If you don't scale/save as jpg, a photo could be quite big. A solution would be to save it on "disk" in sandbox immediately (with jpeg format would be a good idea anyway) and store in your array only the path of the file you saved.

    See a sample code:

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* imgName = [NSString stringWithFormat:@"%@.jpg", self.uid];
        NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imgName];
        NSData *webData = UIImageJPEGRepresentation(self.theImage, 0.5);
        [webData writeToFile:imagePath atomically:YES];
        self.imageURL = imagePath;