objective-c - 如何处理带空格的文件名?

标签 objective-c xcode cocoa error-handling spaces

我使用下面的代码来复制在文件浏览器中选择的文件,并将其复制到具有不同名称的临时目录中。但是,当我选择其中包含空格的文件时,程序会抛出错误,指出找不到指定的精细路径。我尝试过使用转义方法,但它们也不起作用。还有其他方法可以处理带空格的文件名吗?

代码从这里开始:

[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
    [openPanel close];

    if (result == NSFileHandlingPanelOKButton) {
        myString = [self randomStringWithLength:7];
        NSString *filePath = [[[openPanel URLs] objectAtIndex:0] absoluteString];

        NSLog(@"%@", filePath);

        NSString *strTemp = [self extractString:filePath toLookFor:@"//" skipForwardX:2 toStopBefore:@".png"];
        NSLog(@"%@",strTemp);
        NSString *realThing = [strTemp stringByReplacingOccurrencesOfString:@"%20" withString:@"\\ "];
        //strTemp = [strTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", realThing);

        NSString* fullPath = [NSString stringWithFormat:@"/tmp/%@.png", myString];
        NSLog(fullPath);


        NSError *error = nil;
        [[NSFileManager defaultManager] copyItemAtPath:realThing toPath:fullPath error:&error];
        if(error) {
            NSLog(@"Error!!!");
            NSLog(@" error => %@ ",error);
        }
        else {
            NSLog(@"Saved to temp directory");
        }

有人有这方面的经验吗?谢谢

最佳答案

将 URL 转换为路径过于复杂且容易出错。 只需使用 path 方法:

NSString *filePath = [[[openPanel URLs] objectAtIndex:0] path];

或者,使用 copyItemAtURL:... 而不是 copyItemAtPath:...

您还应该检查 copyItemAtPath:...返回值作为指示器 失败:

if (![[NSFileManager defaultManager] copyItemAtPath:filePath toPath:fullPath error:&error]) {
    NSLog(@" error => %@ ",error);
}

比较 Handling Error Objects Returned From Methods :

Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

关于objective-c - 如何处理带空格的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201047/

相关文章:

objective-c - 仅在需要时提供精确的数字 - 这可能吗?

swift - CharacterSet和CharacterSet.inverted打印出来的结果是一样的

ios - 转发类作为父类(super class)

iphone - 自动释放池页面损坏

ios - Facebook Messenger SDK 将文本分享给特定用户

ios - 来自 Swift 3 中路径或文件名的 UIImage

ios - 在已经安装 XCode6 的计算机上安装 XCode5

objective-c - 如何覆盖 NSWindow?

ios - 苹果支付 Stripe : Using apple pay certificate not able build

objective-c - 在 Mac 应用程序中使用钥匙串(keychain)中的证书