我正在尝试将一个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;
}
在视图控制器或UIWindow中调用EXC_BAD_ACCESS
后会导致 [self.view addSubview:alertView]
。
答案 0 :(得分:9)
您有两个层(self.layer
和self.alertLayer
),它们具有相同的委托self
,这会在添加此视图时导致内部方法-[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:]
中的无限递归( self
)到视图树。因此,您必须删除self.alertLayer.delegate = self;
以避免崩溃。如果您需要委派alarmLayer
,则可以创建不同的对象。