我创建了以下类来获取带有彩色图像的工具栏
@interface likeUIBarButtonItem : UIBarButtonItem
- (id) initWithStatus: (enum ApartmentLikeStatus)p_status;
@end
,m文件如下所示:
- (IBAction) likeStatus_Clicked: (id) sender
{
self.numberOfClicks++;
[self.statusButton setImage:[self getStatusImage] forState:UIControlStateNormal];
}
- (id) initWithStatus: (enum ApartmentLikeStatus)p_status
{
self.statusButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.statusButton setImage:[self getStatusImage] forState:UIControlStateNormal];
[self.statusButton addTarget:self action:@selector(likeStatus_Clicked:) forControlEvents:UIControlEventTouchUpInside];
[self.statusButton setFrame:CGRectMake(0, 0, 20, 20)];
self = [[likeUIBarButtonItem alloc] initWithCustomView:self.statusButton];
return self;
}
在视图控制器中,我执行以下操作:
likeUIBarButtonItem* stausBtn = [[likeUIBarButtonItem alloc] initWithStatus:self.apartmentToShow.userLikness];
// List of toolbaritems
NSArray* toolbarItems = [NSArray arrayWithObjects: stausBtn, nil];
self.toolbarItems = toolbarItems;
self.navigationController.toolbarHidden = NO;
按钮显示但单击时我得到汇编代码
0x120a09f: movl (%edi), %esi <-- thread 1: EXC_BAD_ACCESS (code=2 address=0x0)
虽然我的statusButton被声明为(strong, nonatomic)
,我猜它会在init和函数调用之间释放,是这样的情况还是其他的?无论如何解决它?
答案 0 :(得分:1)
这不是您覆盖init*
方法的方式。
你可能会更喜欢这样的事情
- (instancetype)initWithStatus:(enum ApartmentLikeStatus)status
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[self getStatusImage] forState:UIControlStateNormal];
[button addTarget:self action:@selector(likeStatus_Clicked:) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 20, 20)];
self = [super initWithCustomView:button];
if (self) {
self.statusButton = button;
}
return self;
}
您的版本存在的问题是您创建了一个按钮并将其分配给self
,但随后您将self
重新分配给最后一个全新的对象。所以最初的self
可能会被立即释放,因为没有其他人可以处理它,这基本上意味着你将一个悬空指针传递给initWithCustomView:
方法