iOS UIFont caching?

孤人 提交于 2020-01-12 13:51:21

问题


I am trying to figure out if I should cache [UIFont fontWithName:@"myfont" size:24]. I am reusing this font in many places. I am wondering if iOS is already caching this for me because font caching is very common at OS level.

Can someone comment on this?

Thanks.


回答1:


Last time I checked, system fonts were cached (i.e. calling [UIFont systemFontOfSize:foo] twice returned you the same object). I'm not sure how often the cache flushes, but it would seem very silly to not cache fonts, since they're instantiated all the time during nib loading.

Of course, if you're doing it twice in the same function, it's slightly faster to cache it in a local variable (and it reduces code size, since Obj-C method calls are huge!). If you're doing it sporadically in different places, it might not be worth the effort.

That said, you may want to access the font through a class method or a method on a "singleton" (e.g. [MyAppBranding titleFont] or [[MyAppBranding currentBranding] titleFont]). This means you can change the font used much more easily, lets you add an extra layer of caching if you notice it's a performance bottleneck, and makes it much easier to support multiple brands.




回答2:


I am wondering if iOS is already caching this for me because font caching is very common at OS level.

that's what iOS (I only tested on iOS 6.1) does.

I just wanted to implement my own caching. You know because I am a smart guy and font loading is probably not very fast.

Turns out people at Apple are smart too. The objects returned by fontWithName:size: are the same for equal fontNames and equal sizes. There is a caching mechanism in place.

To confirm this I put a couple of NSLogs throughout the app.

NSLog(@"GillSans 12 %p", [UIFont fontWithName:@"GillSans" size:12.0f]);

They all show the same memory address.

Works with your custom fonts too.



来源:https://stackoverflow.com/questions/7641549/ios-uifont-caching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!