【发布时间】:2010-12-15 17:57:17
【问题描述】:
我正在使用 Core Data 框架开发数据库应用程序。在这个应用程序中,我需要显示应用程序当前在 iPhone 上使用了多少数据。有没有办法做到这一点?
【问题讨论】:
-
除此之外一个应用程序可以在iphone中存储多少数据???
标签: iphone cocoa cocoa-touch core-data
我正在使用 Core Data 框架开发数据库应用程序。在这个应用程序中,我需要显示应用程序当前在 iPhone 上使用了多少数据。有没有办法做到这一点?
【问题讨论】:
标签: iphone cocoa cocoa-touch core-data
Core Data 中的持久存储只是文件系统上的一个文件。当您创建 Core Data 堆栈时,您可以访问并可能创建此文件。以下代码将打印持久存储的大小和文件系统的可用空间,以字节为单位:
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]);
这假定您的持久存储名为persistentstore.sqlite,并存储在您的应用程序的文档目录中。如果您不确定持久存储的名称,请查找分配并初始化 NSPersistentStoreCoordinator 的位置。商店的名称应该在附近的代码中指定。
请注意,您从文件和文件系统属性字典中返回的值是 NSNumber,因此如果您想以这种方式处理文件大小,则需要将它们转换为标量类型。需要注意的一件事是这些值以字节为单位,因此对于多 GB 文件系统,您可能会遇到 32 位整数数据类型的数字大小限制。
【讨论】:
我发现this answer on the Apple Dev Forums 可用于查找应用主目录分区上的可用磁盘空间(请注意,目前每个设备上有两个分区)。
使用NSPersistentStoreCoordinator 获取您的商店收藏。
使用NSFileManager 获取每个存储的大小(以字节为单位)(unsigned long long)
NSArray *allStores = [self.persistentStoreCoordinator persistentStores];
unsigned long long totalBytes = 0;
NSFileManager *fileManager = [NSFileManager defaultManager];
for (NSPersistentStore *store in allStores) {
if (![store.URL isFileURL]) continue; // only file URLs are compatible with NSFileManager
NSString *path = [[store URL] path];
DebugLog(@"persistent store path: %@",path);
// NSDictionary has a category to assist with NSFileManager attributes
totalBytes += [[fileManager attributesOfItemAtPath:path error:NULL] fileSize];
}
请注意,上面的代码在我的应用委托的方法中,它有一个属性persistentStoreCoordinator。
【讨论】:
不确定我在哪里看到的,但我相信从数据库中删除条目不一定会缩小数据库文件。 SQLite 在内部回收存储并重新使用它。 (这是典型的 RDBMS。)我相信某个地方有一个命令行实用程序可以压缩它,但是如果您的应用程序想要将文件缩小到数据集(例如,为操作系统回收空间),这对您没有帮助.
因此,虽然文件大小方法可以让您了解数据库的高水位线大小,但它不一定会告诉您数据集使用的存储量。
【讨论】: