问题
The problem is removing an item that´s been written using writeToFile:
method, I cannot seem to remove it. I tried NSFileManager but I guess these are two different types of storage.
- (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;
}
I add the objects using the writeToFile
method of NSData, I guess this must be the problem, since it uses plist to store while NSData something else, if it is - how do I remove this item written with writeToFile
?:
[object writeToFile:destinationString atomically:YES];
Error message removing file
ERROR REMOVING OBJECT: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0xd4c4d40 {NSURL=/Users/bruker/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/14480FD3-9B0F-4143-BFA4-728774E7C952/Documents/FavoritesFolder/2innernaturemusic}
回答1:
If your file is present at that path you can try this:
[[NSFileManager defaultManager] removeItemAtPath:[destinationURL path] error:&error];
Hope this helps.
回答2:
And the "for some reason": your "URL" is just a path, it's not a valid filesystem URL. For that, you would need to prepend file://
before the actual path, or even better, use [NSURL fileURLWithPath:]
.
回答3:
In this place
result = [fileManager removeItemAtURL:destinationURL error:&removeError];
NSLog(@"ERROR REMOVING OBJECT: %@",removeError);
you log and do not check the result value. Is it really NO
? You should check return value first, and then if it is NO
, check the removeError
.
And also I prefer to write
NSError * removeError = nil;
when declarate it. May be removeError
object contains some old information.
来源:https://stackoverflow.com/questions/17568890/nsfilemanager-removing-item