3

该方法enumerateAttributesInRange获取一个代码块并为其中的每个属性执行它NSAttributedString

  • 它会异步调用 bock 吗?

当我的应用程序冻结后,以下方法连续调用两次真的很快 1,我想知道这是因为 enumerateAttributesInRange 异步运行代码块,所以 2 个线程正在尝试同时修改我的 AttributedString。

- (void) doSomething
{
   //following line works fine
   [self doSomethingwithAttributedString];

   //following line works fine
   [self doSomethingwithAttributedString];
   [self performSelector:@selector(doSomethingwithAttributedString) withObject:nil afterDelay:1];

   //following crashes
    [self doSomethingwithAttributedString];
    [self doSomethingwithAttributedString];
}

- (void)doSomethingwithAttributedString
{
   [self.attributedString enumerateAttributesInRange:_selectedRange options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:
 ^(NSDictionary *attributes, NSRange range, BOOL *stop) {

          // Here I modify the dictionary and add it back to my attributedString
 }];
}
4

2 回答 2

5

您正在枚举属性字符串时对其进行修改。我敢打赌,这彻底混淆了枚举器,因为它正在处理的属性字符串不在它开始枚举时的状态。在块中,只收集属性,例如在字典或数组中,但修改它们并将它们应用到字符串之后,即在枚举完成之后。

换句话说:不要将修改属性字符串的代码放在枚举期间调用的块内。文档说您可以在该块适用的范围内修改属性字符串,但 ISTM 您必须非常小心不要外出。我不会这样做的。

于 2011-07-23T01:26:27.373 回答
0

我有点晚了,但添加[self.attributedString beginEditing];之前和[self.attributedString endEditing];之后似乎可以解决崩溃。

于 2012-10-27T08:39:26.467 回答