Nic*_*Nic 7 iphone cocoa cocoa-touch core-data
我正在使用Core Data框架处理数据库应用程序.在这个应用程序中,我需要显示应用程序当前在iPhone上使用了多少数据.有没有办法做到这一点?
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]);
Run Code Online (Sandbox Code Playgroud)
这假设您的持久存储已命名persistentstore.sqlite并存储在应用程序的文档目录中.如果您不确定持久存储的名称,请查找您分配和初始化NSPersistentStoreCoordinator的位置.应该在那里的代码中的某处指定商店的名称.
请注意,从文件和文件系统属性字典中返回的值是NSNumbers,因此如果要以这种方式处理文件大小,则需要将它们转换为标量类型.需要注意的一点是这些值以字节为单位,因此对于数GB的文件系统,您可能会遇到32位整数数据类型的数字大小限制.
我发现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];
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面的代码是我的app委托的方法,它有一个属性persistentStoreCoordinator.
| 归档时间: |
|
| 查看次数: |
5502 次 |
| 最近记录: |