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.
Brad larson
source share