2014-06-22 3 views
1

Objective-C에서 명령 줄 응용 프로그램을 사용하여 읽고있는 RTF 파일이 있습니다. 나는이 질문에서 데이브 드롱의 코드를 사용하고 있습니다 : How to read data from NSFileHandle line by line?Objective-C에서 RTF 파일을 읽으려고 시도합니다.

내 문제는 내 출력은 다음과 같이 나오고 것을 :

2014-06-21 20:03:45.578 AjrumTest[5663:303] {\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf200 
    2014-06-21 20:03:45.579 AjrumTest[5663:303] {\fonttbl\f0\fnil\fcharset0 LucidaGrande;\f1\fnil\fcharset178 AlBayan;\f2\froman\fcharset0 TimesNewRomanPSMT; 
    2014-06-21 20:03:45.580 AjrumTest[5663:303] \f3\fnil\fcharset178 GeezaPro;} 
    2014-06-21 20:03:45.580 AjrumTest[5663:303] {\colortbl;\red255\green255\blue255;} 
    2014-06-21 20:03:45.581 AjrumTest[5663:303] \margl1440\margr1440\vieww10800\viewh8400\viewkind0 
    2014-06-21 20:03:45.581 AjrumTest[5663:303] \deftab720 
    2014-06-21 20:03:45.581 AjrumTest[5663:303] \pard\pardeftab720 
    2014-06-21 20:03:45.582 AjrumTest[5663:303] 
    2014-06-21 20:03:45.582 AjrumTest[5663:303] \f0\fs46 \cf0 1 
    2014-06-21 20:03:45.582 AjrumTest[5663:303] \f1 - \'de\'f3\'dc\'c7\'e1\'f3 \'c7\'c8\'fa\'dc\'e4\'f5 \'c2\'c8\'f3\'f8 \'e6\'f3\'c7\'d3\'fa\'e3\'f5\'dc\'e5\'f5 \'e3\'f5\'cd\'f3\'e3\'f3\'f8\'dc\'cf\'f5 
... 

내가 실감 나는에서 독서하고있는 문서가 RTF 파일이기 때문에 그, 필요한 속성을 첨부해야합니다. 나는이 같은 main 메소드에서 내 파일에 전달합니다

- (NSString *) readLine { 
    if (currentOffset >= totalFileLength) { 
     return nil; 
    } 
    NSData *newLineData = [lineDelimiter dataUsingEncoding:NSUTF8StringEncoding]; 
    [fileHandle seekToFileOffset:currentOffset]; 
    NSMutableData * currentData = [[NSMutableData alloc] init]; 
    BOOL shouldReadMore = YES; 

    @autoreleasepool { 

     while (shouldReadMore) { 
      if (currentOffset >= totalFileLength) { 
       break; 
      } 
      NSData *chunk = [fileHandle readDataOfLength:chunkSize]; 
      NSRange newLineRange = [chunk rangeOfData_dd:newLineData]; 
      if (newLineRange.location != NSNotFound) { 

       //include the length so we can include the delimiter in the string 
       chunk = [chunk subdataWithRange:NSMakeRange(0, newLineRange.location+[newLineData length])]; 
       shouldReadMore = NO; 
      } 
      [currentData appendData:chunk]; 
      currentOffset += [chunk length]; 
     } 
    } 

    NSDictionary *attrs = @{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType, NSWritingDirectionAttributeName:@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]}; 

    NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:currentData options:attrs documentAttributes:nil error:nil]; 

    //NSLog(@"What does this give me? %@", [attrString string]); 
    //The above line outputs (null) for [attrString string] 
    NSString *line = [[NSString alloc] initWithData:currentData encoding:NSUTF8StringEncoding]; 
    return line; 

} 

- (NSString *) readTrimmedLine { 
    return [[self readLine] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
} 

#if NS_BLOCKS_AVAILABLE 
- (void) enumerateLinesUsingBlock:(void(^)(NSString*, BOOL*))block { 
    NSString *line = nil; 
    BOOL stop = NO; 
    while (stop == NO && (line = [self readLine])) { 
     block(line, &stop); 
    } 
} 
#endif 

내가 올바른 문서가 NSAttributedString은를 작성하기 전에을 NSData 객체에 속성을 연결할 때 :

여기
 NSString *pathToMyFile = [[NSBundle mainBundle] pathForResource:@"MyRTFDocument" ofType:@"rtf"]; 
     DDFileReader * reader = [[DDFileReader alloc] initWithFilePath:pathToMyFile]; 
     [reader enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { 
      NSLog(@"%@", line); 
     }]; 

문서가 다음 구문 분석하는 방법이다 내가 정확히 작동하는 다음 코드는 내가 원하는 한 다른 아이폰 OS 응용 프로그램에서

NSDictionary *attrs = @{NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType, NSWritingDirectionAttributeName:@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]}; 
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:currentData options:attrs documentAttributes:nil error:nil]; 
NSLog(@"%@", [attrString string]); 

:, I가 null 객체를 얻을

출력 내용이 정확하도록 NSAttributedString 객체에 문서 속성을 올바르게 연결하려면 명령 행 응용 프로그램에해야하는 것을 누구나 볼 수 있습니까?

미리 답변 해 주신 모든 분께 감사드립니다.

+1

비슷한 문제가있었습니다. rtf의 내용을 txt 파일에 복사하여 수정할 수 있습니다. –

답변

0

나는 즉시 대답을 가지고 있지만,이 코드 줄에 관해서하지 않습니다

NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:currentData options:attrs documentAttributes:nil error:nil]; 

당신은 결과가 null 인 이유/전무를 파악하는 오류 변수를 사용해야합니다. 그래서 대신 다음과 같이 작성하십시오 :

NSError *error = nil; 
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:currentData options:attrs documentAttributes:nil error:&error]; 

If (attrString == nil) // parsing failed, so read out error 
{ 
    NSLog(@"%@", error); 
} 

아마도 이것은 잘못된 점을 파악하는 데 도움이됩니다.

+0

제안 해 주셔서 대단히 감사드립니다. 오류 메시지는 다음과 같습니다. 오류 도메인 = NSCocoaErrorDomain 코드 = 256 "파일을 열 수 없습니다." – syedfa

+0

경로가 올바른지 확인해야합니다. 경로가 잘못되어 파일을 열 수 없기 때문일 수 있습니다. –

+0

문서가 URL에서 오지는 않지만 문서에 별도의 파일로 포함되어 있습니다. NSLog를 통해 포맷팅 데이터를 가져오고 있다는 사실은 문제의 파일을 읽었다는 것을 알려줍니다. – syedfa

관련 문제