Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a CALayer sublayer inside of UIView init

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.

Init method:

- (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.

like image 260
davey555 Avatar asked Apr 12 '13 19:04

davey555


1 Answers

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.

like image 132
Vitaly Berg Avatar answered Nov 07 '22 12:11

Vitaly Berg