3

我只学习 Cocoa/Objective C 几天了,所以很抱歉这可能很简单/很明显,但这让我很困惑。

我已经编写了这个处理程序,用于将 3 个浮点数保存到一个文本文件中。但是,当我运行它时,文件没有被保存。任何人都可以建议我的代码中是否存在错误,或者您是否认为还有其他东西(例如文件写入权限)阻止了文件被写入。

研究使我研究了沙盒,但这很快就变得令人困惑,我希望仅在调试中从 xcode 运行应用程序就可以让我写入我的用户目录。

继承人的代码:

- (IBAction)saveResultsAction:(id)sender {

    //Sets up the data to save
    NSString *saveLens = [NSString stringWithFormat:@"Screen width is %.02f \n Screen Height is %.02f \n Lens is %.02f:1",
        self.myLens.screenWidth,
        self.myLens.screenHeight,
        self.myLens.lensRatio];

    NSSavePanel *save = [NSSavePanel savePanel];

    long int result = [save runModal];

    if (result == NSOKButton) {
        NSURL *selectedFile = [save URL];
        NSLog(@"Save URL is %@", selectedFile);
        NSString *fileName = [[NSString alloc] initWithFormat:@"%@.txt", selectedFile];
        NSLog(@"Appended URL is %@", fileName);
        [saveLens writeToFile:fileName
                   atomically:YES
                     encoding:NSUTF8StringEncoding
                        error:nil];
    }
}
4

3 回答 3

2

NSURL 对象不是 POSIX 路径..

它是一个 URL 并获取它的描述不会使它成为一个路径


NSString *fileName = [selectedFile.path stringByAppendingPathExtension:@"txt"];


但如前所述,您根本不必附加 .txt 。只需使用面板返回的内容。否则,会出现沙盒错误,因为您无权访问修改后的文件名:)

NSString *fileName = selectedFile.path;

于 2012-12-26T18:16:33.063 回答
1

问题是您不需要将文件扩展名附加到 URL。扩展名已经存在。您可以直接这样做:

if (result == NSOKButton)
{   
    [saveLens writeToURL: [save URL]
                atomically:YES
                  encoding:NSUTF8StringEncoding
                     error:nil];
}
于 2012-12-26T17:27:29.103 回答
1

NSError我看到您已经接受了答案,但了解如何使用指针调试此类问题也可能会有所帮助。

Cocoa 使用NSErrorwith 方法调用来生成错误条件,从而丰富地封装错误。(Objective-C 也有例外,但它们是为程序员错误的情况保留的,例如数组索引超出范围,或者永远不应该出现的 nil 参数。)

当您有一个接受错误指针的方法时,通常它还会返回一个BOOL指示整体成功或失败的值。以下是获取更多信息的方法:

NSError *error = nil;
if (![saveLens writeToFile:fileName
                atomically:YES
                  encoding:NSUTF8StringEncoding
                     error:&error]) {
    NSLog(@"error: %@", error);
}

甚至:

NSError *error = nil;
if (![saveLens writeToFile:fileName
                atomically:YES
                  encoding:NSUTF8StringEncoding
                     error:&error]) {
    [NSApp presentError:error];
}
于 2012-12-26T23:59:37.890 回答