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

时间:2011-04-25 14:21:31

标签: iphone objective-c loading

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

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

想象一下,将字符串@“NoteBook.txt”传递给以下方法,并且App的Docs文件夹中没有这样的文件:

 -(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];
        }
    }

}

感谢您的任何建议,我真的很感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

问题是你正在检查是否设置了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
}

答案 1 :(得分:1)

你的代码中已经有了它:

    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。