简体   繁体   English

如果自定义UIView包含> 1个子层,则应用在touches上崩溃开始,为什么?

[英]If custom UIView has >1 sublayers, app crashes on touchesBegan, why?

I have a few custom UIView objects that all handle drawing like this: 我有一些自定义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];
}

They also have a - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; 它们还具有- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; with nothing else inside but a NSLog . 除了NSLog里面什么也没有。

I add them all inside my main ViewController like so: 我将它们全部添加到主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];
}

When I run my app, if I tap on a view that has only a single layer - I get my NSLog to show, and everything's fine. 当我运行我的应用程序时,如果我点击只有一个图层的视图-我将显示我的NSLog ,一切都很好。 If, on the other hand, I tap on views with 1+ layers, the app crashes ( objc_msgSend log shows up with "EXC_BAD_ACCES (code=1, address=...") . I guess this is somehow related with ARC , which I have enabled. 另一方面,如果我点击1层以上的视图,则应用程序崩溃( objc_msgSend日志显示为"EXC_BAD_ACCES (code=1, address=...") 。我想这与ARC有关,我已启用。

How do I add multiple layers to a view, without it being messed up by ARC ? 如何在视图中添加多个图层,而不会被ARC弄乱呢?

I don't think that this is an ARC problem, but creating and inserting the layers in drawRect is wrong. 我不认为这是ARC问题,但是在drawRect创建和插入图层是错误的。 This should be done (only once) in the init method of the view, eg in initWithFrame . 这应该在视图的init方法中完成(仅一次),例如initWithFrame

In my case, the solution was definitely related to ARC. 就我而言,解决方案肯定与ARC有关。

When initialising my delegates, I immediately assigned them to the layer.delegate property, and ARC would remove the object from existence immediately after that. 在初始化我的委托时,我立即将他们分配给layer.delegate属性,并且ARC将在此之后立即将对象从存在中删除。

So for each layer, I add a strong @property (strong, nonatomic) delegatesClass *delegatesName and initialise straight to the property. 因此,对于每一层,我都添加了一个强大的 @property (strong, nonatomic) delegatesClass *delegatesName并直接对该属性进行初始化。 After that, I assign the layer.delegate = self.delegatesName . 之后,我指定layer.delegate = self.delegatesName

This did solve the issue, although I'm not sure if it is the right way to do things. 这确实解决了问题,尽管我不确定这是否是正确的处理方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM