5

我正在尝试将 CALayer 添加为 UIView 子类中的子层,但是当我在 init 方法中添加子层EXC_BAD_ACCESS时,我会在将视图添加到另一个视图或窗口时得到。

初始化方法:

- (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[self.view addSubview:alertView]是在视图控制器或 UIWindow 内部调用后引起的。

4

1 回答 1

9

您有两个具有相同委托的层 (self.layer和),当将此视图 ( ) 添加到视图树时,这会导致内部方法中的无限递归。因此,您必须删除以避免崩溃。如果您需要委托,您可以创建不同的对象。self.alertLayerself-[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:]selfself.alertLayer.delegate = self;alarmLayer

于 2013-04-12T20:16:01.073 回答