More time to display NSAttributed string with custom fonts

I am showing an NSAttributed row column using Core Text. It is working fine. When using the system font, it is displayed without any delays both in the simulator and on the device. But when using a custom font, it takes longer to display content on the device. But in the simulator, the result is quick.

- (void)updateAttributedString { // Existing Code if (self.text != nil) { self.attributedString = [[NSMutableAttributedString alloc] initWithString:self.text]; NSRange range = NSMakeRange(0, [self.text length]); // Regarding Fixed font // [ self.attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"TAUN_Elango_Abirami" size:20] range:range];//This is my custom font // Regarding custom Font using below code if (self.font != nil) { CTFontRef font = [self createCTFont]; [self.attributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:range]; CFRelease(font); } } } - (CTFontRef)createCTFont; { CTFontRef font = CTFontCreateWithName((CFStringRef)self.fontName, self.pointSize, NULL); return font; } 

If I add the following line of code,

  [self.attributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:range]; 

the display of the attribute string in the device is slower. But in the simulator it is fast. If I do not add this piece of code, the text will be displayed quickly both in the simulator and on the device.

0
source share
1 answer

Create your font object once and hold it. I would probably cache them in a static dictionary if you have a lot and need to share between objects. Do not create a new one every time you update a row. A font object will almost certainly do all its complex work of decoding at the point where you first need it (and not that you created it). System fonts are always downloaded and decoded, but custom fonts are probably not supported if nothing refers to them.

You can also experiment with UIFont , not CTFont here. UIFont is a higher level object, and my experience is that it caches more. I have not studied this situation. In general, you should usually use UIKit types if you really don't need Core Text. This can be counter-intuitive, since "is no lower level faster?" Well, a lower level can be faster if you know exactly what you are doing. But in fact, a lower level simply means "you need to take more care of yourself." Trusting UIKit is usually the best first-order solution until you find out that you need something smaller.

No wonder the simulator will be faster. It runs on a Mac, which has significantly more processing power and a much faster drive than the iPhone. When you run things on a simulator, they are really just Mac apps that run in a dedicated user interface; It is not a complete emulator like Android.

0
source

Source: https://habr.com/ru/post/974514/


All Articles