当我更新我的iOS应用程序时,我想删除Documents目录中的任何现有sqlite数据库.现在,在应用程序更新时,我将数据库从软件包复制到文档目录,并通过附加软件包版本来命名它.因此,在更新时,我还想删除可能存在的任何旧版本.
我只是希望能够删除所有sqlite文件,而无需循环浏览并查找以前版本的文件.是否有任何方法可以对removeFileAtPath:方法进行通配符?
解决方法
那么,你想要删除所有* .sqlite文件?无法避免循环,但您可以通过使用nspredicate首先过滤掉非sql文件并使用快速枚举确保快速性能来限制循环.这是一种方法:
- (void)removeAllsqliteFiles
{
NSFileManager *manager = [NSFileManager defaultManager];
// the preferred way to get the apps documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
Nsstring *documentsDirectory = [paths objectAtIndex:0];
// grab all the files in the documents dir
NSArray *allFiles = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
// filter the array for only sqlite files
nspredicate *fltr = [nspredicate predicateWithFormat:@"self ENDSWITH '.sqlite'"];
NSArray *sqliteFiles = [allFiles filteredArrayUsingPredicate:fltr];
// use fast enumeration to iterate the array and delete the files
for (Nsstring *sqliteFile in sqliteFiles)
{
NSError *error = nil;
[manager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:sqliteFile] error:&error];
NSAssert(!error,@"Assertion: sqlite file deletion shall never throw an error.");
}
}