Objective-c:加载简单txt文件时如何处理错误

发布于 2024-11-03 09:07:12 字数 1602 浏览 2 评论 0原文

我正在尝试将一个简单的 TXT 文件加载到 NSMutableArray 中。我的文件名为 NoteBook.txt。出于以下目的(处理错误),我删除了 NoteBook.txt,以便应用程序实际上无法加载它。

在下面的代码中,我尝试找出我想要加载的文档文件夹中是否存在该文件。下面的代码实际上不应该尝试加载该文件,因为没有文件。然而,它仍然如此,我想知道我做错了什么?

想象一下,字符串@“NoteBook.txt”被传递到以下方法,并且应用程序的文档文件夹中没有这样的文件:

 -(void) loadNoteBook:(NSString *)nameOfNoteBook
{

    NSLog(@"Starting method 'LoadNoteBook...'");

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    //NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"NoteBook.txt"];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:nameOfNoteBook];
    NSError *error;

    if (filePath) { // check if file exists - if so load it:
        NSLog(@"Loading notebook: %@", nameOfNoteBook);

        NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
                                                          encoding:NSUTF8StringEncoding
                                                             error:&error];

        self.NoteBook = [[[tempTextOut componentsSeparatedByString: @"\n*----------*\n"] mutableCopy] autorelease];
    }
    else
    {   
        // GENERATE mutable ARRAY

        NSLog(@"Loading notebook failed, creating empty one...");

        NoteBook = [[NSMutableArray alloc] init];

        for (int temp = 0; temp < 6; temp++) {
            [NoteBook insertObject:@"Empty" atIndex:temp];
        }
    }

}

感谢您的任何建议,我非常感谢您的帮助。

I'm trying to load a simply TXT file into a NSMutableArray. My file is called NoteBook.txt. For the following purposes (handling errors), I deleted NoteBook.txt so that the App could actually NOT load it.

In the following code, I try to find out if the file exist in my Docs Folder which I'd like to load. The following code should actually NOT attempt to load the file as there isn't one. However, it does so nonetheless and I am wondering what I am doing wrong?

Imagine that the string @"NoteBook.txt" is passed to the following method and that there is no such file in the Docs Folder of the App:

 -(void) loadNoteBook:(NSString *)nameOfNoteBook
{

    NSLog(@"Starting method 'LoadNoteBook...'");

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    //NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"NoteBook.txt"];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:nameOfNoteBook];
    NSError *error;

    if (filePath) { // check if file exists - if so load it:
        NSLog(@"Loading notebook: %@", nameOfNoteBook);

        NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
                                                          encoding:NSUTF8StringEncoding
                                                             error:&error];

        self.NoteBook = [[[tempTextOut componentsSeparatedByString: @"\n*----------*\n"] mutableCopy] autorelease];
    }
    else
    {   
        // GENERATE mutable ARRAY

        NSLog(@"Loading notebook failed, creating empty one...");

        NoteBook = [[NSMutableArray alloc] init];

        for (int temp = 0; temp < 6; temp++) {
            [NoteBook insertObject:@"Empty" atIndex:temp];
        }
    }

}

Thanks for any suggestions, I'd really appreciate your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月苍老的讽刺 2024-11-10 09:07:12

问题是您正在检查 NSString 是否已设置,而不是路径本身。

您应该做的是使用 NSFileManager fileExistsAtPath:isDirectory:

BOOL isDir;

NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && !isDir) {
    //file exists and is not a directory
}

The problem is that you're checking if the NSString is set, not the path itself.

What you should probably do is check the path with NSFileManager fileExistsAtPath:isDirectory:

BOOL isDir;

NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && !isDir) {
    //file exists and is not a directory
}
蓝咒 2024-11-10 09:07:12

您已经在代码中得到了它:

    NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];

    if(!tempTextOut) {
        if(error) {
            // error specific code to execute
            NSLog(@"error loading file %@: %@", filePath, error);
        } 

        // GENERATE mutable ARRAY

        NSLog(@"Loading notebook failed, creating empty one...");

        NoteBook = [[NSMutableArray alloc] init];

        for (int temp = 0; temp < 6; temp++) {
            [NoteBook insertObject:@"Empty" atIndex:temp];
        }

    } else {
       self.NoteBook = [[[tempTextOut componentsSeparatedByString: @"\n*----------*\n"] mutableCopy] autorelease];

    }

您在 filePath 上进行测试,它实际上只是您创建的一个字符串。您不测试其后面是否有文件。即使

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

确实返回空字符串,您仍然将 nameOfNoteBook 附加到它,并且如果放入 if 语句,则针对非空字符串的测试将评估为 true。

You've got it already in your code:

    NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];

    if(!tempTextOut) {
        if(error) {
            // error specific code to execute
            NSLog(@"error loading file %@: %@", filePath, error);
        } 

        // GENERATE mutable ARRAY

        NSLog(@"Loading notebook failed, creating empty one...");

        NoteBook = [[NSMutableArray alloc] init];

        for (int temp = 0; temp < 6; temp++) {
            [NoteBook insertObject:@"Empty" atIndex:temp];
        }

    } else {
       self.NoteBook = [[[tempTextOut componentsSeparatedByString: @"\n*----------*\n"] mutableCopy] autorelease];

    }

You test on filePath, which is actually just a string you've created. You don't test if there is a file behind it. Even if

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

does return an empty string you still append nameOfNoteBook to it and will if put in an if statement, testing against a non empty string will evaluate to true.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文