繁体   English   中英

NSFileManager:删除项目

[英]NSFileManager: removing item

问题是要删除使用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编写的writeToFile

[object writeToFile:destinationString atomically:YES];

错误消息删除文件

错误删除对象:错误域= NSCocoaErrorDomain代码= 4“操作无法完成。(可可错误4。)” UserInfo = 0xd4c4d40 {NSURL = /用户/ bruker /库/Application%20Support/iPhone%20Simulator/6.1/ Applications / 14480FD3-9B0F-4143-BFA4-728774E7C952 / Documents / FavoritesFolder / 2innernaturemusic}

如果您的文件位于该路径中,则可以尝试以下操作:

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

希望这可以帮助。

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

在这个地方

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

您登录并且不检查结果值。 难道真的NO 您应该首先检查返回值,然后如果它为NO ,则检查removeError

而且我更喜欢写

NSError * removeError = nil;

声明时。 可能是removeError对象包含一些旧信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM