【发布时间】:2013-07-08 06:42:27
【问题描述】:
问题是删除使用writeToFile: 方法编写的项目,我似乎无法删除它。我试过 NSFileManager 但我猜这是两种不同类型的存储。
- (BOOL) removeObject: (NSString *)objectToRemove inCategory:(StorageType)category
{
BOOL result = NO;
NSError *removeError;
NSString *storageFolder = [self getCategoryFor:category];
if (objectToRemove) {
NSFileManager *fileManager = [[NSFileManager alloc]init];
// Find folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:storageFolder];
NSString *dataPathFormated = [dataPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
NSLog(@"Removing file error: folder was not found");
}
NSURL *destinationURL = [[NSURL alloc]initWithString:[NSString stringWithFormat:@"%@/%@",dataPathFormated,objectToRemove]];
//NSString *destinationString = [NSString stringWithFormat:@"%@/%@",dataPath,objectToRemove];
if ([fileManager fileExistsAtPath:[destinationURL path]]) {
NSLog(@"destination URL for file to remove: %@", destinationURL);
// Remove object
result = [fileManager removeItemAtURL:destinationURL error:&removeError];
NSLog(@"ERROR REMOVING OBJECT: %@",removeError);
} else {
NSLog(@"Object to remove was not found at given path");
}
}
return result;
}
我使用 NSData 的 writeToFile 方法添加对象,我想这一定是问题所在,因为它使用 plist 来存储 NSData 其他东西,如果是的话 - 我如何删除这个用 writeToFile 编写的项目?:
[object writeToFile:destinationString atomically:YES];
删除文件的错误信息
错误删除对象:错误域=NSCocoaErrorDomain 代码=4“ 操作无法完成。 (Cocoa 错误 4.)" UserInfo=0xd4c4d40 {NSURL=/Users/bruker/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/14480FD3-9B0F-4143-BFA4-728774E7C952/Documents/FavoritesFolder/2innernaturemusic}
【问题讨论】:
-
任何 NSLog 正在执行?
-
@Midhun:当然是忘记贴错误信息了
-
代替
result = [fileManager removeItemAtURL:destinationURL error:&removeError];使用:result = [fileManager removeItemAtURL:[destinationURL path] error:&removeError]; -
Midhun:这几乎可以工作,除了它返回一个字符串而不是 URL,所以我将其更改为 [fileManager removeItemAtPath:[destinationURL path] error:&removeError];由于某种原因现在可以正常工作
-
@TomLilletveit 我还添加了一个解释原因的答案。您应该阅读文档,而不是对这些方法的作用做出假设。
标签: ios objective-c persistence nsfilemanager writetofile