自定义块上的EXC_BAD_ACCESS [英] EXC_BAD_ACCESS on customised blocks
问题描述
我在一个类中定义了一个块:
I defined a block in a class:
BXButton.h
BXButton.h
typedef void(^ButtonClicked)(id sender, NSDictionary *userInfo);
@property (assign, nonatomic) ButtonClicked onButtonClicked;
- (void)setClickBlock:(ButtonClicked)buttonClicked;
BXButton.m
BXButton.m
- (void)setClickBlock:(ButtonClicked)buttonClicked {
onButtonClicked = buttonClicked;
}
- (void)internalButtonClicked {
DLog(@"internal clicked");
if (self.onButtonClicked) {
onButtonClicked(self, self.userInfo);
}
}
我试图在视图控制器中这样调用:
And I tried to call like this in a view controller:
[_testButton setClickBlock:^(BXButton *sender, NSDictionary *userInfo) {
DLog(@"userInfo %@", userInfo);
[sender startLoading];
[[BXAPIClient sharedPublicClient]postPath:@"/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
[sender endLoading];
//[safeSelf stop];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[sender endLoading];
[self stop];
}];
}];
每当我尝试访问[self方法]或在块外部定义的任何变量时,我总是得到BAD_ACCESS.有任何想法吗?谢谢!
And I always got BAD_ACCESS whenever I try to access [self method] or any variable which is defined outside of the block. Any ideas? Thanks!
推荐答案
得到EXC_BAD_ACCESS
的原因是因为默认情况下在堆栈上创建了块,因此,如果使用assign
属性引用它们,它们将简单地堆栈被拆毁后,它便不再存在.
The reason why you get EXC_BAD_ACCESS
is because blocks are created on the stack by default, so if you reference them with an assign
property they will simply cease to exist when the stack gets teared down.
为了解决这个问题,您应该将块复制到堆中.
一种方法是在定义属性时使用copy
而不是assign
.
In order to fix this you should copy the block into the heap.
One way to do that is to use copy
instead of assign
when defining your property.
将声明更改为
@property(copy, nonatomic) ButtonClicked onButtonClicked;
,并在分配块时使用其setter/getter而不是直接访问ivar
and use its setter/getter instead of accessing directly to the ivar when assigning a block
- (void)setClickBlock:(ButtonClicked)buttonClicked {
self.onButtonClicked = buttonClicked;
}
- (void)internalButtonClicked {
DLog(@"internal clicked");
if (self.onButtonClicked) {
self.onButtonClicked(self, self.userInfo);
}
}
这篇关于自定义块上的EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!