objective-c - UIButton:单击时崩溃

标签 objective-c crash uibutton

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

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

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

然后我添加“A”,从 NSObject 派生的接口(interface),带有 UIImageView 和“B”数组:
A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];


@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


- (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

我不明白错在哪里!

如果我直接从主视图 Controller 在按钮上添加目标,则有效
A* a = [[A alloc] initWithImageView:self.imageView];
[A loadButtons];
for(B* b in a.b) {
    [b.button addTarget:self action:@selector(bClicked:) forControlEvents:UIControlEventTouchUpInside];
} 

最佳答案

单纯看你的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 作为 subview 添加到 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 对象没有被释放。

关于objective-c - UIButton:单击时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606173/

相关文章:

objective-c - mutableCopy 是否使包含的对象可变?

iphone - 这是从 NSArray 中删除空白字符串的正确且最有效的方法吗?

ios - NSPredicate 返回所有对象

ios - 调整导航 Controller 中自定义 UIBarButtonItem 的大小

ios - 将目标添加到 UIButton 不起作用

objective-c - 如何使用 Cocoa 在 PDF 中生成网格?

service - 应用程序停止时 Android GCM 崩溃

iphone - 应用因WebView而崩溃

C++ delete [] 对象导致崩溃

iphone - 按下时如何获取 UIButton 的标题