title: Thread safety in Objective-C categories
body: <p>I have a category on NSString:</p>
  
  <pre><code>- (CGSize) agb_sizeWithFont:(UIFont *)font width:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode {
      if (!font) return CGSizeZero;
  
      NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
      paragraphStyle.lineBreakMode = lineBreakMode;
      NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil];
  
      // this line is not threadsafe
      NSAttributedString *as = [[NSAttributedString alloc] initWithString:self attributes:attributes];
  
      CGRect bounds = [as boundingRectWithSize:CGSizeMake(width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) context:nil];
      return CGSizeMake(width, bounds.size.height);
  }
  </code></pre>
  
  <p>I've observed intermittent <code>EXC_BAD_ACCESS</code> crashes when running this code on multiple threads (sometimes in <code>initWithString: attributes:</code>, sometimes in <code>boundingRectWithSize:options:context:</code>).</p>
  
  <p>I believe my code is not thread-safe because <code>self</code> might deallocate on one thread while <code>initWithString: attributes:</code> is executing on the other.</p>
  
  <ol>
  <li>Is my conclusion about this method's thread safety correct?</li>
  <li><p>Would this code make it thread-safe?</p>
  
  <pre><code>NSString *strongSelf = self;
  NSAttributedString *as = [[NSAttributedString alloc] initWithString:strongSelf attributes:attributes];
  </code></pre>
  
  <p>(By maintaining a reference to <code>self</code>, I attempt to ensure the object in memory is not deallocated while I'm using it.)</p></li>
  <li><p>Is there any way to declare this method as <em>not thread-safe</em>?  I'd love to generate a warning, for example, if a string declared as a <code>nonatomic</code> property is passed into this method.</p></li>
  </ol>
  
  <p>Note: In case it's not obvious, I'm using ARC.</p>