【问题标题】:Delete image from app directory in iPhone从 iPhone 的应用程序目录中删除图像
【发布时间】:2012-03-13 23:40:35
【问题描述】:

我想从我的 iPhone 应用程序中删除一张图片。 我使用下面的方法,将图像的名称作为参数传递。

问题是图片没有被删除。

- (void)removeImage:(NSString*)fileName {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@.png", fileName]];

    [fileManager removeItemAtPath: fullPath error:NULL];
    NSLog(@"image removed: %@", fullPath);

    NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
    NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
}

最后两行显示了我的应用目录中的内容,我要删除的图像仍然存在。我做错了什么?

【问题讨论】:

    标签: ios iphone image uiimage delete-file


    【解决方案1】:

    您正在尝试删除 Documents 目录中的文件。然后阅读捆绑资源目录的内容。这些不是同一个目录。

    如果您尝试删除 Documents 目录中的文件,您应该在 NSLog() 最后将该目录添加到该目录。如果您尝试删除捆绑包中的文件,这是不可能的。 App Bundle 已签名,无法修改。

    【讨论】:

    • 我正在尝试删除我在 XCode 中添加的图像,所以它可能在我的包中。这是默认图像。我正在尝试删除这个并添加一个新的。
    • 您不能删除 AppBundle 中的图像(这些是您在 Xcode 中添加的图像)。
    • 我不能替换默认图像,而不是删除它吗?
    【解决方案2】:

    您的代码看起来不错,因此请尝试在您的代码中添加一些“NSError”对象:

    - (void)removeImage:(NSString*)fileName {
    
       NSFileManager *fileManager = [NSFileManager defaultManager];
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,   YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"%@.png", fileName]];
    
       NSError *error = nil;
       if(![fileManager removeItemAtPath: fullPath error:&error]) {
          NSLog(@"Delete failed:%@", error);
       } else {
          NSLog(@"image removed: %@", fullPath);
       }
    
       NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
       NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
    }
    

    在上面的代码中,我传递了一个NSError removeItemAtPath 的错误参数。如果系统无法删除该文件,此方法将返回NO,并用引发的错误填充error 对象。

    【讨论】:

    • "操作无法完成。没有这样的文件或目录" 如何搜索文件或文件夹?因为似乎还有另一个文件夹保存图像。
    • 那么你把图片保存在哪里了。
    【解决方案3】:

    根据您的评论,我发现您正在尝试删除 default.png 并将其替换为另一个。不幸的是,这是不可能的。图像 default.png 是应用程序包的一部分,一旦创建和签名就无法修改(这是 Apple 的一项安全措施,因此应用程序在审核后无法更改)。您可以创建和删除文件的唯一位置是在为您的应用程序提供的沙箱内(Documents 文件夹)。

    【讨论】:

    猜你喜欢
    • 2011-12-29
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2013-12-13
    相关资源
    最近更新 更多