I want to ask how to combine x number of attributed string and make a single string.
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:health.storeArry];
NSLog(@"%lu",(unsigned long)array.count);
for (NSDate * str in array) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
NSString * dateTimeString = [dateFormatter stringFromDate:str];
NSString* str=dateTimeString;
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:str];
[attrString addAttribute: NSFontAttributeName value: [UIFont fontWithName:@"Helvetica" size:15] range: NSMakeRange(str.length-2,2)];
NSLog(@"%@",attrString);
[attrString appendAttributedString:attrString];
}
This is my code. I found ans of two or three attibutedstring cancatenated but I have an array in which x number nsdate
objects. I want to concatenate all of them in one string. How can I achieve that?
Thanks
Your issue is that you were creating each time a new NSMutableAttributedString
. You need to put it outside the for loop.
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:health.storeArry];
NSLog(@"%lu",(unsigned long)array.count);
NSMutableAttributedString *finalAttributedString = [NSMutableAttributedString alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
dateFormatter.timeStyle = NSDateFormatterShortStyle;
for (NSDate *str in array) {
NSString *dateTimeString = [dateFormatter stringFromDate:str];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:dateTimeString];
[attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Helvetica" size:15] range:NSMakeRange(str.length-2,2)];
NSLog(@"%@",attrString);
[finalAttributedString appendAttributedString:attrString];
}
//Here, you can read the finalAttributedString
Not related tip: You should alloc/init the NSDateFormatter
outside the for loop. It's always the same one, and plus alloc/init of NSDateFormatter
is consuming.