开发者

iOS UIFont caching?

I am trying to figure out if I should cache [UIFont fontWithName:@"myfont" size:24]. I am reusing this font in many plac开发者_如何学运维es. 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜