【问题标题】:UIButton: crash on clickUIButton:单击时崩溃
【发布时间】:2015-06-18 19:31:30
【问题描述】:

前提是我已经阅读了所有类似的 S.O.线程,我还没有找到适合我的解决方案。

我有一个带有按钮的 imageView 控制器,并且工作正常。

UIImage* image = [UIImage imageNamed:@"background"];
[self.imageView setImage:image];

然后我添加“A”,从 NSObject 派生的接口,带有 UIImageView 和“B”数组:

A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];

啊.h

@interface A : NSObject
@property (nonatomic, strong) UIImageView* imageView;
- (void)loadButton;
@end

上午

- (id)initWithImageView:(UIImageView*)imageView {
    self = [super init];
    self.myArray = [[NSMutableArray alloc] init];
    self.imageView = imageView;
    return self;
}

- (void)loadButton {
    B* b = [[B alloc] init];
    [self.myArray addObject:b];
    [self.imageView addSubview:b.button];
}

B.h

@interface B : NSObject 
@property (nonatomic, strong) UIButton* button;
@end

B.m

- (id)init {
    self = [super init];
    self.button = [[UIButton alloc] init];
    self.button.frame = CGRectMake(0, 0, 20, 20);
    [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    return self;
}

- (void)buttonClicked:(id)sender {
 ...
}

现在的问题是,当用户单击按钮时,应用程序崩溃在控制台上报告没有错误,但在 main 上移动:

0x10ab52900 <+1282>: movq   0xb56001(%rip), %rax      ; (void *)0x000000010cdfd070: __stack_chk_guard

我不明白哪里错了!

如果我直接从主视图控制器在按钮上添加目标

A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
for(B* b in a.b) {
    [b.button addTarget:self action:@selector(bClicked:) forControlEvents:UIControlEventTouchUpInside];
} 

【问题讨论】:

  • 为所有异常添加断点。下次崩溃时看看它在哪里崩溃。
  • 已经完成了,不起作用..
  • 你在哪里调用你的initWithDictionary:方法?
  • 请发布堆栈跟踪。
  • 你真的实现了buttonClicked: 方法吗?您声称有效的代码引用了一个名为bClicked: 的方法,而不是buttonClicked:。它是哪个?如果您发布相关的堆栈跟踪,指出导致崩溃的实际行并发布错误消息,将会有所帮助。

标签: objective-c crash uibutton


【解决方案1】:

单纯看你的A.h和A.m,有问题

- (id)initWithImageView:(UIImageView*)imageView {
    self = [super init];
    self.myArray = [[NSMutableArray alloc] init];
    self.imageView = imageView;
    return self;
}

- (void)loadButton {
    B* b = [[B alloc] init];
    [self.myArray addObject:b];
    [self.imageView addSubview:b.button];
}

您的变量 b 将在 loadButton 方法退出后被释放!因此,即使您将 b.button 作为子视图添加到 self.imageView,单击按钮也会使您的程序崩溃。

但在你的第二个例子中,

A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
for(B* b in a.b) {
    [b.button addTarget:self action:@selector(bClicked:) forControlEvents:UIControlEventTouchUpInside];
} 

不知何故,b 是 A 的属性(为什么我在 A.h 中没有看到)?你修改了吗?如果您修改 A.h 以包含指向 B 的强指针,那么代码将起作用,因为您的 b 对象没有被释放。

【讨论】:

  • 好吧,再看一遍,您确实将 b 添加到 self.myArra (在 h 文件中再次找不到)。您应该正确生成所有相关代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
相关资源
最近更新 更多