Your persistent store in Core Data is just a file on the file system. You access and possibly create this file when you create your Core Data stack. The following code will print the size of a persistent store and the free space of the file system, 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 store is named persistentstore.sqlite
and is stored in the documents directory for your application. If you are uncertain as to the name of your persistent store, look for where you alloc and init your NSPersistentStoreCoordinator. The name of the store should be specified somewhere in the code around there.
Note that the values you get back from the file and file system attributes dictionaries are NSNumbers, so you'll need to convert them to scalar types if you want to work with the file sizes in that manner. One thing to be careful of is that these values are in bytes, so for multi-gigabyte filesystems you might run into number size limitations with 32-bit integer data types.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…