Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

iphone - How do I find the size of my Core Data persistent store and the free space on the file system?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...