NSFileManager:删除项目

Tom*_*eit 0 persistence objective-c nsfilemanager ios writetofile

问题是删除使用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;
}
Run Code Online (Sandbox Code Playgroud)

我使用writeToFileNSData 的方法添加对象,我想这肯定是问题所在,因为它使用plist在NSData中存储其他东西(如果存在)-我如何删除用writeToFile?编写的该项:

[object writeToFile:destinationString atomically:YES];
Run Code Online (Sandbox Code Playgroud)

错误消息删除文件

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

小智 5

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

    [[NSFileManager defaultManager] removeItemAtPath:[destinationURL path] error:&error];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。