Uibutton Actions not firing in ARC mode where As they are firing in non ARC mode

63 Views Asked by At

In View Controller.m

@interface ViewController ()
{
    CustomView *view;
}

@implementation ViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    view = nil;
    view = [[CustomView alloc]init];

    [self.view addSubview:view];
}

In CustomView.m

-(CustomView *)init
{
    CustomView *result = nil;
    result = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];

    return result;
}

I have two buttons in my custom view. My Custom view was loaded fine as expected but button actions not fired if enable ARC for CustomView.m file, If I disable ARC then Button actions are firing…

Where Im going wrong..

Is it the correct way of loading a nib of uiview (which i want to use in many places in my project..)

Thank you ..

1

There are 1 best solutions below

8
On

This is a very confusing/confused implementation of an init method.

- (CustomView *)init
{
    CustomView *result = nil;
    result = [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];

    return result;
}

I'd suggest changing it to something like this...

// class method not instance method
+ (CustomView *)loadFromNib {
    return [[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil] objectAtIndex:0];
}

Then changing your ViewController method to something like this...

@interface ViewController ()

@property (nonatomic, strong) CustomView *customView; // don't call it view, it's confusing

@end

@implementation ViewController

-(void)viewDidLoad {
    [super viewDidLoad];

    self.customView = [CustomView loadFromNib];

    [self.view addSubview:self.customView];
}

The problems you are having are possibly coming from the way you implemented the init method as an instance method but then ignored the instance and returned a new instance.

The memory implications of that are confusing and hard to work out.