在view中我使用AFJSONRequestOperation下载数据,然后在success语法块中创建了一个按钮,在我点击这个按钮的时候,程序就crash了。
crash输出如下。
2013-11-01 11:35:47.898 JinglunPlatform[2914:c07] -[UIView buttonClick:]: unrecognized selector sent to instance 0x8462da0
2013-11-01 11:35:47.899 JinglunPlatform[2914:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView buttonClick:]: unrecognized selector sent to instance 0x8462da0'
*** First throw call stack:
(0x2531012 0x21dfe7e 0x25bc4bd 0x2520bbc 0x252094e 0x21f3705 0x11272c0 0x1127258 0x11e8021 0x11e857f 0x11e76e8 0x13eb1d3 0x24f9afe 0x24f9a3d 0x24d77c2 0x24d6f44 0x24d6e1b 0x2f077e3 0x2f07668 0x1123ffc 0x6172 0x24a5)
libc++abi.dylib: terminate called throwing an exception
(lldb)
我创建按钮的代码如下。
AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 50, 20)];
[button setImage:[UIImage imageNamed:@"btn_arrow_normal.png"] forState:UIControlStateNormal];
[button addTarget:self.superview action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
[button release];
}
网上一番搜索之后发现,原来是因为,addTarget后面跟的第一个参数self.superview变成了局部变量,然后在点击的时候就找不到这个已经释放掉的局部变量了。
解决的方法是,在类中定义一个成员变量,然后将这个参数换成这个成员变量。代码如下。
@property (strong, nonatomic) UIView * clickTarget;
//然后在类的初始化方法中。
self.clickTarget = self.superView;
//然后在使用的时候将self.superView替换为self.clickTarget。