iOS Sandbox Disk Management and Cleaning Strategies
The article explains iOS sandbox storage by detailing the four main directories, their backup rules, naming conventions, and retrieval APIs, then outlines how to calculate physical file size and implements both automatic quota‑based and manual user‑driven cleaning methods, including system cache removal for tmp, WKWebView, and dyld caches.
In iOS app development, disk management is a critical factor that directly impacts user experience and application performance. This article presents practical guidance on iOS sandbox file storage, directory APIs, storage conventions, and both automatic and manual disk‑cleaning mechanisms.
iOS Sandbox Overview
The iOS sandbox isolates each app in its own file system, consisting of four main directories: MyApp.app , Documents , Library , and tmp . MyApp.app is read‑only and contains the executable and resources. Documents stores user‑generated content and is backed up by iCloud. Library holds non‑user data (e.g., Application Support , Caches , Preferences ) and is backed up except for Caches . tmp is for temporary files and is not backed up.
Directory Retrieval APIs
// Get sandbox home directory
NSString *homeDir = NSHomeDirectory();
// Get Documents directory
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
// Get Library directory
NSString *libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
// Get Caches directory
NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// Get tmp directory
NSString *tmpDir = NSTemporaryDirectory();
// Get app bundle path
[[NSBundle mainBundle] bundlePath];File Storage Conventions
MyApp.app : read‑only resources; developers must not write here.
Documents : user‑generated files; should only contain data intended for user access and iCloud backup.
Documents/Inbox : files imported via external sharing; developers should not create files here, only read/delete.
Library/Application Support : app configuration and data files; not for cache data.
Library/Caches : re‑downloadable or regenerable data (e.g., image caches); not backed up, may be purged when storage is low.
Library/Preferences : user defaults; developers should not create files manually.
tmp : temporary files; should be deleted promptly after use.
File Naming Rules
Use PascalCase for folder names.
Limit business data to three levels of sub‑directories: one under Library , one under Library/Caches , and one under Documents .
iCloud Backup Considerations
Only Documents and Library (excluding Caches ) are synced to iCloud. Files that should not be backed up must have the NSURLIsExcludedFromBackupKey set once when the file is created.
NSURL *pathurl = [NSURL fileURLWithPath:path];
BOOL success = NO;
success = [pathurl setResourceValue:@(YES) forKey:NSURLIsExcludedFromBackupKey error:nil];Disk Size Calculation
File size obtained via attributesOfItemAtPath: reflects logical size, not physical disk usage. Physical usage can be calculated using stat :
+ (unsigned long long)fileSizeOnDisk:(nonnull NSString *)filePath {
struct stat fileStat;
int res = stat([filePath cStringUsingEncoding:NSUTF8StringEncoding], &fileStat);
if (-1 == res) { return 0; }
long long fileSize = fileStat.st_blocks / 8 * fileStat.st_blksize;
return fileSize;
}Disk Cleaning Strategies
Automatic Cleaning
Defines business‑specific quota limits, disk‑level states (Normal, Warning, Critical), and triggers based on level changes, app version upgrades, or time intervals. Business modules register a cleanup protocol; the disk component invokes each module sequentially.
Manual Cleaning
Provides a UI for users to select items to clean, including deep cleaning and user‑asset management (videos, images, PDFs, etc.).
System Cache Cleaning
tmp Directory : Identify files matching patterns (e.g., CFNetworkDownload , WKWebFileUpload ) and delete them. + (NSArray<NSURL *>)calculateTmpSysCache { NSArray *regexPatterns = @[@"CFNetworkDownload", @"WKWebFileUpload", @"NSIRD_", @"正在存储文稿"]; NSString *tmpPath = NSTemporaryDirectory(); if (!tmpPath) return @[]; NSMutableArray *tmpNeedCleanCache = [NSMutableArray array]; NSFileManager *fileManager = [NSFileManager defaultManager]; for (NSString *fileName in [fileManager enumeratorAtPath:tmpPath]) { NSString *fullPath = [tmpPath stringByAppendingPathComponent:fileName]; NSURL *fileURL = [NSURL fileURLWithPath:fullPath]; if ([self shouldCleanFile:fullPath patterns:regexPatterns]) { [tmpNeedCleanCache addObject:fileURL]; } } return tmpNeedCleanCache; }
WKWebView Cache : Use WKWebsiteDataStore to remove specific data types or domain‑specific caches. // Remove all cache types since epoch NSSet *websiteDataTypes = [NSSet setWithArray:@[ WKWebsiteDataTypeCookies, WKWebsiteDataTypeLocalStorage, WKWebsiteDataTypeIndexedDBDatabases, WKWebsiteDataTypeWebSQLDatabases, WKWebsiteDataTypeFetchCache, WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeOfflineWebApplicationCache ]]; NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0]; [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{ NSLog(@"Cache cleared"); }];
dyld Cache (iOS 13) : Clean tmp/com.apple.dyld or retain only the newest file on older systems. + (void)cleanTmpDyld { NSString *tmpDyldPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/com.apple.dyld"]; if ([[NSFileManager defaultManager] fileExistsAtPath:tmpDyldPath]) { if (@available(iOS 14.0, *)) { [PFMDiskSizeUtils cleanupDirectoryAtPath:tmpDyldPath]; } else { [PFMDiskSizeUtils cleanDiskCaches:tmpDyldPath reservedCountLimit:1]; } } }
Summary
The article systematically explains iOS sandbox storage, provides concrete API examples, defines naming and backup rules, and proposes a comprehensive disk‑cleaning framework that combines automatic quota‑based cleaning with user‑initiated actions. Future posts will cover disk monitoring and anomaly handling.
Baidu Geek Talk
Follow us to discover more Baidu tech insights.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.