2014-08-28 1 views
0
나는 다음과 같은 코드를 사용하여 파일을 생성

:NS 방법에 의해 반환 된 오류를 처리하는 블록을 사용하는 방법

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??) 

이 내가 (디버깅을 위해) 파일을 다시 읽기 위해 사용하고있는 코드는 다음과 같습니다

를 NSE '호환되지 않는 유형의 매개 변수에

보내기'무효 (^) (무효) '

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

나는 말한다 마지막 문장에 2 빌드 오류를 얻고있다 rror * __ autoreleasing의 * '

및 선언되지 않은 식별자의

사용'오류 '

이 내가 방법은 오류를 반환 처리하기 위해 블록을 사용하고 처음입니다; SO 또는 Google에서이 작업을 수행하는 방법을 보여주는 문서를 찾을 수 없습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

+5

블록을 'NSError **'유형의 매개 변수로 전달할 수 있다고 생각하십니까? – rmaddy

+0

어 ... 나는 그것을 예를 들어 보았다 ... 잘못되었다, 응? 그것은 * 블록 *에 문제가 있습니다. SD – SpokaneDude

답변

1

이 함수는 블록이 아니라 NSError** 매개 변수를 필요로합니다. 여러분이 호출해야하는 방식은 다음과 같습니다 :

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

이것은 오류 상태를 확인하는 올바른 방법이 아닙니다. Apple의 "Error Handling Programming Guide"에 설명되어 있듯이 * 반환 값 *,이 경우'if (content == nil)'을 항상 확인하고 반환 값이 오류를 나타내는 경우에만 오류 변수를 평가해야합니다. –

+0

@ MartinR 좋은 지적, 고정. 나는 최근 node.js에서 너무 많은 시간을 보내고 있었고, 나 자신보다 조금 앞서 갔다. –

+0

RATS! rmaddy의 코멘트에 대한 내 의견에서 언급했듯이 Google을 검색 할 때 오류 처리기로 사용 된 블록을 보았습니다 ... 그럼 내 다음 질문은 블록을 사용할 수 있는지 여부를 어떻게 알 수 있습니까? – SpokaneDude

관련 문제