2

I am calling sizeWithFont on a background thread, this sizeWithFont is located on the drawRect, which is called on an NSOperationQueue on a background thread. I occasionally had random crashes on the sizeWithFont. I've been googling around and it seems some say this is an issue on apple. What's a better way to fix this then?

It is said in the documentation the following as of iOS 4:

Drawing to a graphics context in UIKit is now thread-safe. Specifically: The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads. String and image drawing is now thread-safe. Using color and font objects in multiple threads is now safe to do.

I have something like this:

 titleSize = [storyTitleString sizeWithFont:[UIFont fontWithName:kProximaNovaBold size:15] constrainedToSize:CGSizeMake(200, kCellMaximumTitleHeight) lineBreakMode:UILineBreakModeWordWrap];

in my drawRect. You can replace storyTitleString with any string you want. And I also using this library to perform drawing in background thread.

adit
  • 32,574
  • 72
  • 229
  • 373

1 Answers1

4

UIKit is not threadsafe, so you cannot call anything on background threads, it will cause intermittent bugs. Your best bet is to either compute everything you need from UIKit before operation starts on main thread, or switch to main thread during your operation run, depends on what you're trying to accomplish.

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
  • 2
    as of iOS 4 UIKit is thredsafe, can be seen here http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniOS/Articles/iPhoneOS4.html – adit Feb 19 '13 at 22:30
  • 1
    Right but not all of it, basically you can draw on context on background and especially draw string, but as you can see, not everything is 100% true in apple docs :) Can you post more code so I can try to test and help? – Dmitry Shevchenko Feb 19 '13 at 23:01
  • or is there an easier way to calculate the size of a string in a background thread without using sizeWithFont – adit Feb 19 '13 at 23:19
  • 1
    Can you give the full operation code? without your business related stuff, just the way contexts are setup, string is drawn etc – Dmitry Shevchenko Feb 19 '13 at 23:30