Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Attributed String and Retain Formatting

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 );
like image 452
DenVog Avatar asked Nov 30 '22 10:11

DenVog


1 Answers

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);
like image 145
rmaddy Avatar answered Dec 05 '22 12:12

rmaddy