Search code examples
iosxcodecore-datainstruments

CoreData: Disk usage increases every time a NSData attribute is accessed


TL:DR - I have a NSData attribute where I save camera images and every time I access that attribute my disk usage increases.

Long Version: My application has a Photo class that I use to save pictures taken from the camera. This is the automatically generated code for it:

@interface Photo : NSManagedObject

@property (nonatomic, retain) NSData * original;
@property (nonatomic, retain) NSData * thumbnail;
@property (nonatomic, retain) NSDate * createdAt;
@property (nonatomic, retain) Patient *patient;

@end

Both *originaland *thumbnail have been set with Allows External Storage in the xcdatamodel file. Each photo object, after being saved, uses about 4MB of space. At one point in the code, I do this:

NSData *original = photo.original

For some reason, the first time the line is run, for each object, disk space usage by the app increases by 4MB. It is as if for some reason Core Data was duplicating and saving again the data contained in photo.original

I have no idea why this happens, and Instruments hasn't helped since the core data profile doesn't work with devices and the simulator has no support for camera.

Anyone has any ideas on what the problem might be?


Solution

  • Sounds reasonable behavior to me. When NSData instances are loaded the system will try to keep that buffer in memory. But if they're too big, your data will end up in virtual memory, backed by cache files. On iPhone 4S, the largest image capture is 3264×2448, which can easily translate to the 4MB files you are seeing.

    Change your Core Data model so that you only keep the file paths. Then keep the images intact as separate files.