这就是我在iOS应用中检索数据,保存和删除的方法。我还首先使用delete修改对象,然后继续。这是我的归档器对象中的三个方法的代码:
+ (id)retrieve:(NSString *)key {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.archive", key]];
return [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
+ (BOOL)persist:(id)object key:(NSString *)key {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.archive", key]];
return [NSKeyedArchiver archiveRootObject:object toFile:filePath];
}
+ (BOOL)delete:(NSString *)key {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.archive", key]];
return [fileManager removeItemAtPath:filePath error:NULL];
}
目前,retrieve:
和persist:
工作正常但delete:
非常不一致;也许是1/100次,它会被正确删除。我不确定这是我的方法导致错误,或者我得到filePath
的方式是不正确的。
我做过一些研究,看起来我不是唯一一个经历过此研究的人?