当我有一个图像时,我插入了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)
解决方法
抛出异常是因为您在使用foreach循环枚举子层数组时更改子层数组的内容.这对于图层来说不是特别的,当您在枚举任何NSMutableArray时添加/删除对象时会抛出类似的异常.
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"];