I'm trying to add a CALayer as a sublayer in a UIView subclass, but when I add the sublayer inside the init method I get EXC_BAD_ACCESS
when I add the view to another view or window.
- (id)initWithTitle:(NSString *)title message:(NSString *)message
{
if ((self = [super init]))
{
self.title = title;
self.message = message;
self.alertLayer = [[CALayer alloc] init];
self.layer.cornerRadius = kCORNER_RADIUS;
self.layer.shadowRadius = 3.0;
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(15, 20);
self.layer.shadowOpacity = 1.0;
self.alertLayer.delegate = self;
self.alertLayer.masksToBounds = YES;
self.alertLayer.cornerRadius = kCORNER_RADIUS;
[self.layer addSublayer:self.alertLayer]; // This line of code seems to cause EXC_BAD_ACCESS
}
return self;
}
EXC_BAD_ACCESS
is caused after calling [self.view addSubview:alertView]
inside a view controller or UIWindow.
You have two layers (self.layer
and self.alertLayer
) which have the same delegate self
, this leads to an infinite recursion in internal method -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:]
when added this view (self
) to the view tree. Therefore you must remove self.alertLayer.delegate = self;
to avoid crash. If you need to delegate for alarmLayer
you can create distinct object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With