Gold Challenge: EXC_BAD_ACCESS if overriding initializer?


#1

Hi there. I’m stumped.

I’ve created a BNRContainer that satisfies the requirements of the Gold Challenge.

However I am getting some strange behaviour.

I am initializing the BNRContainers in main.m like so:

BNRContainer *container = [[BNRContainer alloc] init];
BNRContainer *secondContainer = [[BNRContainer alloc] init];

My designated initializer for BNRContainer is declared in the header and its implementation is:

- (instancetype)initWithItemName:(NSString *)name valueInDollars:(int)value serialNumber:(NSString *)sNumber items:(NSMutableArray *)items
{
    self = [super init];
    if (self) {
        _itemName = name;
        _valueInDollars = value;
        _serialNumber = sNumber;
        _subitems = items;
    }
    return self;
            
}

Also in the implementation, I am overriding init, like so:

- (instancetype)init
{
    return [self initWithItemName:@"Container" valueInDollars:0 serialNumber:@"" items:[[NSMutableArray alloc] init]];
}

However, if I override initWithItemName:, even if I don’t call it anywhere, I get a runtime error of EXC_BAD_ACCESS(code=2, …), and the method’s only line is highlighted.

The method is:

- (instancetype)initWithItemName:(NSString *)name
{
    return [self initWithItemName:name valueInDollars:0 serialNumber:@"" items:[[NSMutableArray alloc] init]];
}

What’s going on here? Why does overriding init work, but not initWithName:??