0

I'm getting some strange behavior.

UIStackView *stackView = [UIStackView alloc];
stackView = [stackView initWithArrangedSubviews:@[self.subview1,self.subview2]];
[self addSubview:stackView];
[stackView setTranslatesAutoresizingMaskIntoConstraints:NO]
[self addConstraint:[NSLayoutConstraint constraintWithItem:stackView attribute: NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0f constant:0]]

This code runs fine when I'm using the Ipad Air 2 simulator from XCode, but when I actually try to run it on my Ipad Air 2, it crashes when trying to add the layout constraint (last line of the code), complaining that stackView is nil.

Upon stepping through the code, I actually found that stackView is nil after the very first line, the call to [UIStackView alloc]. This is strange to me, as I don't know why an alloc call would return nil, much less why it would return nil only on an actual device instead of the simulation of a device.

Edit:

I originally had the code as follows:

UIStackView * stackView = [[UIStackView alloc] initWithArrangedSubviews:@[self.subview1,self.subview2]];
[self addSubview:stackView];
[stackView setTranslatesAutoresizingMaskIntoConstraints:NO]
[self addConstraint:[NSLayoutConstraint constraintWithItem:stackView attribute: NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0f constant:0]]

In this instance, stackView was nil after the combined alloc/initcall, but I don't know which one made it nil. Thus why I separated out the calls to see.

4oby
  • 607
  • 10
  • 19
Justin
  • 119
  • 9

1 Answers1

0

I believe the problem to be that you are creating your UIStackView incorrectly. It should be created like the following:

UIStackView *stackView = [[UIStackView alloc] init];

It seems that ARC is simply cleaning up the UIStackView immediately because you are not holding a reference to it correctly.

The difference between the actual device and simulator can likely be attributed to ARC working on different intervals on the simulator. Just another reason to always test code on an actual device first! ;)

J-Crew
  • 1
  • 1
  • I had it like you had it to start, but I separated it out into two separate statements, alloc and init. I think that doing the alloc and init calls separately, since I am holding a reference to the UIStackView. – Justin Dec 22 '15 at 21:59
  • Regardless, when I had it like you show, the stackView was nil after the alloc/init call. Meaning that either the alloc or init call failed, and I don't know why – Justin Dec 22 '15 at 21:59