使用Cocoa合并RTF文件

时间:2012-12-23 18:47:27

标签: macos cocoa merge rtf

怎么会这样做?我知道合并NSData不起作用。

1 个答案:

答案 0 :(得分:2)

使用NSAttributedString应该可以工作,类似于下面显示的代码

这是一种将许多RTF文件合并在一起的非常快速和简单的方法

- (void)mergeRTF:(NSURL*)rtf1 :(NSURL*)rtf2 :(NSURL*)merged {
    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    [options setObject:[NSNumber numberWithUnsignedInteger:NSUTF8StringEncoding]
                forKey:NSCharacterEncodingDocumentOption];
    NSDictionary *docAttrs = nil;
    NSError* error = nil;

    NSAttributedString *rtfText1 = [[NSAttributedString alloc] initWithURL:rtf1
                                                               options:options
                                                    documentAttributes:&docAttrs
                                                                 error:&error];

    NSAttributedString *rtfText2 = [[NSAttributedString alloc] initWithURL:rtf2
                                                                options:options
                                                     documentAttributes:&docAttrs
                                                                  error:&error];
    NSMutableAttributedString* whole = [[NSMutableAttributedString alloc] initWithAttributedString:rtfText1];
    [whole appendAttributedString:rtfText2];
    NSData* data = [whole RTFFromRange:NSMakeRange(0, whole.length) documentAttributes:nil];

    [data writeToURL:merged atomically:YES];
}