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

前端 未结 3 2062
粉色の甜心
粉色の甜心 2020-12-13 16:33

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. I

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 17:04

    I found this answer on the Apple Dev Forums to be useful for finding disk space available on the apps' home directory partition (note there are currently two partitions on each device).

    Use NSPersistentStoreCoordinator to get your store collection.

    Use NSFileManager to get each stores' size in bytes (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];
    }
    

    Note that the code above is in a method of my app delegate, and it has a property persistentStoreCoordinator.

提交回复
热议问题