stringWithContentsOfFile期间记录错误消息

时间:2013-04-21 15:12:12

标签: ios objective-c

我正在尝试读取CSV文件。我已经在我的应用程序中导入了该文件,因此该文件位于本地。当我执行下面的这部分代码时:

@autoreleasepool {
    NSError *error;
    NSString *alldata =  [NSString stringWithContentsOfFile:@"config_menu_position.csv"
                                                   encoding:NSUTF16StringEncoding error:&error];
    NSLog(@"alldata: %@", alldata);
    NSLog( @"error: %@", error );
}

我有这个日志错误消息,我的变量总是为nul:

    2013-04-21 17:05:37.571 PageViewController[1578:c07] alldata :(null)
    2013-04-21 17:05:38.242 PageViewController[1578:c07] error: Error Domain=NSCocoaErrorDomain
 Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x7ebf100 
{NSFilePath=config_menu_position.csv, NSUnderlyingError=0x7ebf060 "The operation couldn’t be 
completed. No such file or directory"}

任何想法?

2 个答案:

答案 0 :(得分:2)

您缺少文件的完整路径,请尝试以下操作:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"config_menu_position" ofType:@"csv"];
NSString *alldata = [NSString stringWithContentsOfFile:filePath
                                              encoding:NSUTF16StringEncoding 
                                                 error:&error];

答案 1 :(得分:1)

pathForResource:ofType尝试NSBundle,例如

[[NSBundle mainBundle] pathForResource:@"config_menu_position" ofType:@"csv"]

然后使用A NSString初始值设定项中返回的路径。