当我有图像时,我使用CAGradientLayer插入子图层,
...
layer.name = @"Gradient";
[cell.imageView.layer insertSublayer:layer atIndex:0];
当ImageView没有图像时,我需要删除这个子图层。 我尝试了不同的方法但没有成功。我试过的最后一次是
for (CALayer *layer in cell.imageView.layer.sublayers) {
if ([layer.name isEqualToString:@"Gradient"]) {
[layer removeFromSuperlayer];
}
}
但它给了我一个错误:
CoreData: error: Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. *** Collection <CALayerArray: 0xc1502e0> was mutated while being enumerated. with userInfo (null)
答案 0 :(得分:29)
抛出异常是因为您在使用foreach循环枚举时更改sublayers
数组的内容。这对于图层来说并不特别,在枚举任何NSMutableArray时添加/删除对象时会抛出类似的异常。
您有多种方法可以解决此问题
解决方案1:修改数组后立即停止枚举。
for (CALayer *layer in cell.imageView.layer.sublayers) {
if ([layer.name isEqualToString:@"Gradient"]) {
[layer removeFromSuperlayer];
break;
}
}
解决方案2:不要枚举真实数组,而是使用其副本。
NSArray* sublayers = [NSArray arrayWithArray:cell.imageView.layer.sublayers];
for (CALayer *layer in sublayers) {
if ([layer.name isEqualToString:@"Gradient"]) {
[layer removeFromSuperlayer];
}
}
解决方案3:使用键值编码来保留对渐变图层的引用。
插入后设置:
[cell.imageView.layer insertSublayer:layer atIndex:0];
[cell.imageView.layer setValue:layer forKey:@"GradientLayer"];
检索并删除它
CALayer* layer = [cell.imageView.layer valueForKey:@"GradientLayer"];
[layer removeFromSuperlayer];
[cell.imageView.layer setValue:nil forKey:@"GradientLayer"];