-1

每个人。我在视图中添加了一个按钮并将其设置为在特定条件下隐藏。虽然它仅在我第一次在 iOS5 中加载整个项目时崩溃。第一次之后,它运行良好。除了 Thread1,Xcode 没有给我更多信息……我想知道是否有人可以提供帮助。谢谢转发。

这是一些代码。

测试视图.h

@property (nonatomic, retain) UIButton *testBtn;

测试视图.m

@synthesize testBtn;

-(id)init
{
    self = [super init];
    if (self) {
        testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    }
    return self;
}
- (void)layoutSubviews{
        testBtn.frame = CGRectMake(110, 100, 100, 24);
        [testBtn setHidden:YES];
        [self addSubview: testBtn];
}

测试视图控制器.m

-(void)requestForSth{
       [testView.testBtn setHidden:NO];   //Thread1: EXC_BAD_ACCESS(code=1,address=0x809a3345)
}
4

1 回答 1

1

Hmm, EXC_BAD_ACCESS means that you tried to access invalid memory. In your -init method, you are assigning testBtn to an autoreleased UIButton object.

I believe that if this file were compiled without ARC, this makes sense. Why? Because ownership semantics don't apply when you perform direct assignment. Only by way of your setter method will the correct ownership semantics be applied.

Under ARC, this is solved thanks to a __strong ownership qualifier by default. If you're still adamant about not moving to ARC, then you can simply retain your UIButton before assigning it directly into your instance variable.

Taking a closer look at your code:

- (id)init {
   self = [super init];
   if(self) {
      //you can explicitly retain it
      testBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
      //or route it through your setter method
      [self setTestBtn:[UIButton buttonWithType:UIButtonTypeCustom]];
   }
   return self;
}
于 2013-06-20T08:27:00.053 回答