我对的NSString类别:线程安全
- (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);
}
我(在boundingRectWithSize:options:context:
在initWithString: attributes:
有时,有时)上运行的多个线程的代码时观察到的间歇EXC_BAD_ACCESS
崩溃。
我相信我的代码不是线程安全的,因为self
可能会在一个线程上释放,而initWithString: attributes:
正在另一个线程上执行。
- 我对这种方法的线程安全性的结论是否正确?
此代码是否会使其线程安全?
NSString *strongSelf = self; NSAttributedString *as = [[NSAttributedString alloc] initWithString:strongSelf attributes:attributes];
(通过维持到
self
参考,我试图确保在内存中的对象,而我用它不释放。)有什么办法来声明这种方法不线程安全?例如,如果声明为
nonatomic
属性的字符串被传入此方法,我希望生成警告。
注意:如果不明显,我使用ARC。
是否启用ARC?使用ARC时,对象在执行其方法时不会被释放 –
@BryanChen是,启用ARC。你确定这是类别方法吗? –
从类别和其他方法声明的线程方法之间绝对没有区别。 –