我在我的代码中遇到了与 ARC 自动插入 objc_retains 相关的奇怪崩溃。
我有以下两个课程:
@interface MenuItem : NSObject
@property (weak, nonatomic) id target;
@property (unsafe_unretained, nonatomic) SEL action;
@property (strong, nonatomic) id object;
- (instancetype)initWIthTarget:(id)target action:(SEL)action withObject:(id)object;
- (void)performAction;
@end
@implementation MenuItem
- (void)performAction
{
if (self.target && self.action)
{
if (self.object)
{
[self.target performSelector:self.action withObject:self.object];
}
else
{
[self.target performSelector:self.action];
}
}
}
@end
@interface Widget : NSObject
- (void)someMethod:(id)sender;
@end
在某些时候,我这样实例化一个 MenuItem:
MenuItem *item = [MenuItem alloc] initWithTarget:widget action:@selector(someMethod:) object:nil];
performAction
然后在其他地方我在菜单项上调用:
[item performAction];
在执行中someMethod
我遇到了崩溃:
@implementation Widget
- (void)someMethod:(id)sender
{
// EXEC_BAD_ACCESS crash in objc_retain
}
@end
为什么会这样?