How can you take an existing NSAttributedString and divide it based on a predefined separator while maintaining formatting? It does not seem that componentsSeparatedByString will operate on an NSAttributedString.
My current workaround produces the splits at the correct points, but only outputs an NSString. Thus losing formatting.
NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
// Wish I could do this
// NSArray *separatedArray = [rtfFileAttributedString componentsSeparatedByString:importSeparatorPref];
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];
NSLog( @"Separated array: %@", separatedArray );
You can make use of your split non-attributed string to split up the attributed string. One option would be:
NSData *rtfFileData = [NSData dataWithContentsOfFile:path];
NSAttributedString *rtfFileAttributedString = [[NSAttributedString alloc] initWithData:rtfFileData options:@{NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType} documentAttributes:nil error:nil];
NSString *rtfFileString = [rtfFileAttributedString string];
NSString *importSeparator = @"###";
NSArray *separatedArray = [rtfFileString componentsSeparatedByString:importSeparatorPref];
NSMutableArray *separatedAttributedArray = [NSMutableArray arrayWithCapacity:separatedArray.count];
NSInteger start = 0;
for (NSString *sub in separatedArray) {
NSRange range = NSMakeRange(start, sub.length);
NSAttributedString *str = [rtfFileAttributedString attributedSubstringFromRange:range];
[separatedAttributedArray addObject:str];
start += range.length + importSeparator.length;
}
NSLog(@"Separated attributed array: ", separatedAttributedArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With