Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...