NSFileManager:删除项目

问题是删除使用writeToFile:方法写的项目,我似乎无法删除它。 我试过NSFileManager,但我猜这是两种不同types的存储。

 - (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]; 

错误信息删除文件

(Cocoa error 4.)“UserInfo = 0xd4c4d40 {NSURL = / Users / bruker / Library / Application%20Support / iPhone%20Simulator / 6.1 /应用程序/ 14480FD3-9B0F-4143-BFA4-728774E7C952 /文档/ FavoritesFolder / 2innernaturemusic}

如果你的文件出现在这个path上,你可以试试这个:

  [[NSFileManager defaultManager] removeItemAtPath:[destinationURL path] error:&error]; 

希望这可以帮助。

而“出于某种原因”:你的“URL”只是一个path,它不是一个有效的文件系统URL。 为此,您需要在实际path前加上file:// ,或者甚至更好地使用[NSURL fileURLWithPath:]

在这个地方

 result = [fileManager removeItemAtURL:destinationURL error:&removeError]; NSLog(@"ERROR REMOVING OBJECT: %@",removeError); 

你logging并不检查结果值。 它真的不是吗? 你应该首先检查返回值,如果是NO ,检查removeError

而且我更喜欢写作

 NSError * removeError = nil; 

当宣布它。 可能是removeError对象包含一些旧的信息。