如果自定义 UIView 有 >1 个子层,应用程序在触摸时崩溃开始了,为什么?



我有一些自定义的UIView对象,它们都像这样处理绘图:

- (void)drawRect:(CGRect)rect {
    // ^ I init the layers 1 and 2
    [self.layer insertSublayer:layer1 atIndex:0]; // 1 or more
    [self.layer insertSublayer:layer2 atIndex:1];
}

它们也有一个- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;,里面只有一个NSLog

我将它们全部添加到主ViewController中,如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];
    CustomView *myViewWith1Layer = [[CustomView alloc] initWithFrame:CGRectMake(20, 20, 440, 260)];
    [self.view addSubview:myViewWith1Layer];
    CustomViewLayered *myViewWith2Layer = [[CustomViewLayered alloc] initWithFrame:CGRectMake(40, 260, 200, -120)];
    [self.view addSubview:myViewWith2Layers];
}

当我运行我的应用程序,如果我点击一个视图,只有一个单层-我得到我的NSLog显示,一切都很好。另一方面,如果我点击1+层的视图,应用程序崩溃(objc_msgSend日志显示"EXC_BAD_ACCES (code=1, address=...")。我猜这与ARC有关,我已经启用了。

如何将多个图层添加到视图中,而不会被ARC弄乱?

我不认为这是ARC问题,而是在drawRect中创建和插入图层是错误的。这应该在视图的init方法中完成(仅一次),例如在initWithFrame中。

在我的例子中,解决方案是肯定是与ARC相关。

当初始化我的委托时,我立即将它们分配给layer.delegate属性,并且ARC将在此之后立即删除该对象。

所以对于每一层,我添加一个strong @property (strong, nonatomic) delegatesClass *delegatesName,并直接初始化属性。之后,我赋值layer.delegate = self.delegatesName .

这确实解决了问题,尽管我不确定这是否是正确的做事方式。

最新更新