如何使用块来处理NS方法返回的错误

时间:2014-08-28 16:06:25

标签: objective-c ios7 nsstring objective-c-blocks

我使用以下代码创建了一个文件:

    NSMutableString *tabString = [NSMutableString stringWithCapacity:0];  //  it will automatically expand

//  write column headings  <----- TODO

//  now write out the data to be exported
for(int i = 0; i < booksArray.count; i++)  {
    [tabString appendString:[NSString stringWithFormat:@"%@\t,%@\t,%@\t\n",
                             [[booksArray objectAtIndex:i] author],
                             [[booksArray objectAtIndex:i] binding],
                             [[booksArray objectAtIndex:i] bookDescription]]];
}

if (![self checkForDataFile: @"BnN.tab"])  //  does the file exist?
    [[NSFileManager defaultManager] createFileAtPath:documentsPath contents: nil attributes:nil];  //  create it if not

NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [NSString stringWithFormat:@"%@/%@",documentsPath, @"BnN.tab"]];  //  <---------- userID?
[handle truncateFileAtOffset:[handle seekToEndOfFile]];   //  tell handle where's the file fo write
[handle writeData:[tabString dataUsingEncoding:NSUTF8StringEncoding]];  //position handle cursor to the end of file  (why??)

这是我用来回读文件的代码(用于调试目的):

    //  now read it back
NSString* content = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",documentsPath, @"BnN.tab"]
                                              encoding:NSUTF8StringEncoding
                                                 error: ^{ NSLog(@"error: %@", (NSError **)error);
                                                 }];

我在最后一句话中得到2个构建错误:

  

发送&#39; void(^)(void)&#39;到不兼容类型的参数&#39; NSError * __ autoreleasing *&#39;

  

使用未声明的标识符&#39;错误&#39;

这是我第一次使用块来处理方法返回的错误;我无法在SO或Google中找到任何显示如何执行此操作的文档。我做错了什么?

1 个答案:

答案 0 :(得分:1)

该函数期望NSError**参数,而不是块。你应该调用它的方式是:

NSError *error = nil;
NSString* content = [NSString stringWithContentsOfFile: [NSString stringWithFormat:@"%@/%@", documentsPath, @"BnN.tab"]
                                              encoding: NSUTF8StringEncoding
                                                 error: &error];
if (content == nil) {
    NSLog("error: %@", error);
}