How to find the size of my persistent data store and free space in the file system?

I am working on a database application using a basic data structure. In this application, I need to display how much data the application is currently using on the iPhone. Is there any way to do this?

+7
iphone cocoa-touch cocoa core-data
source share
3 answers

Your persistent storage in Core Data is just a file in the file system. You access and possibly create this file when creating the Core Data stack. The following code will print the size of persistent storage and file system free space in bytes:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *persistentStorePath = [documentsDirectory stringByAppendingPathComponent:@"persistentstore.sqlite"]; NSError *error = nil; NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:persistentStorePath error:&error]; NSLog(@"Persistent store size: %@ bytes", [fileAttributes objectForKey:NSFileSize]); NSDictionary *fileSystemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:persistentStorePath error:&error]; NSLog(@"Free space on file system: %@ bytes", [fileSystemAttributes objectForKey:NSFileSystemFreeSize]); 

This assumes that your persistent storage is named persistentstore.sqlite and is stored in the document directory for your application. If you are unsure of the name of your persistent store, find the place you are pointing to and launch your NSPsistentStoreCoordinator. The name of the store should be indicated somewhere in the code.

Note that the values ​​returned from the file and file system attribute dictionaries are NSNumbers, so you will need to convert them to scalar types if you want to work with file sizes this way. One thing to be careful of is that these values ​​are in bytes, so for file systems with several gigabytes you can use number size limits with 32-bit integer data types.

+9
source share

I do not know where I saw it, but I believe that deleting records from the database will not necessarily lead to compression of the database file. SQLite restores internal storage and reuses it. (This is typical for RDBMSs.) I think that somewhere there is a command line utility, but it will not help you if your application wants to compress the file into a data set (for example, to free up space for the OS).

Thus, while the file size method will give you an idea of ​​the high value of the database database, it will not necessarily tell you the amount of storage used by your data set.

+1
source share

All Articles