2009-11-12 32 views

回答

9

我發現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

+0

非常感謝:-) – Nic 2009-12-10 11:03:16

9

您在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。應該在附近的代碼中指定商店的名稱。

請注意,從文件和文件系統屬性字典中返回的值是NSNumbers,因此如果要以這種方式處理文件大小,則需要將它們轉換爲標量類型。需要注意的一件事是這些值是以字節爲單位的,因此對於數GB的文件系統,您可能會遇到32位整數數據類型的數字大小限制。

+0

謝謝布拉德。它的幫助...... – Nic 2009-11-13 04:55:37

+0

@Brad:你知道系統是否允許應用程序使用文件系統剩餘空間的完整(或關閉)使用?或者,可用空間是否返回系統分配給應用程序的最大值? – mahboudz 2009-11-14 04:45:15

+0

在設備上,它似乎返回內部閃存上的總空間(返回的字節值與iTunes報告的可用空間相匹配)。我認爲應用程序有很多空間可以使用。 – 2009-11-14 05:15:03

1

不知道我在哪看到它,但我認爲從數據庫中刪除條目不一定會縮小數據庫文件。 SQLite在內部回收存儲並重新使用它。 (這是典型的RDBMS)。我相信有一個命令行實用程序可以壓縮它,但如果您的應用程序想要將文件縮小到數據集(例如,爲操作系統回收空間),這不會對您有所幫助。 。

所以雖然文件大小的方法會給你一個數據庫的高水位大小的感覺,但它不一定會告訴你數據集使用的存儲量。

相關問題