Search code examples
objective-cmacosnsmutablearraynsarraynsstackview

Fill NSStackView with NSArray and NSMutableArray


I have a Stack to fill with an array of views.

_countViewArray = [[NSArray alloc] init];
_countViewArray = @[self.a.view,self.b.view,self.c.view];
_stackView = [NSStackView stackViewWithViews:_countViewArray];

It's work well. If I want replace this array with a mutable array how can do it?

I tried this code for a "dynamic" stack view and finally convert mutable array in simple array but doesn't work:

_mutableCountViewArray = [[NSMutableArray alloc] init];

[_mutableCountViewArray addObject:@[self.a.view]];
if (caseCondition){
   [_mutableCountViewArray addObject:@[self.b.view]];
}
[_mutableCountViewArray addObject:@[self.c.view]];

_countViewArray = [_mutableCountViewArray copy];
_stackView = [NSStackView stackViewWithViews:_countViewArray];

in consolle if I print mutable array I have:

(
    (
    "<NSView: 0x600000121ea0>"
),
    (
    "<NSView: 0x600000120780>"
,
    (
    "<NSView: 0x6000001235a0>"
)
)

How can I solve?


Solution

  • The problem is that you are adding arrays (containing a single view) instead of views...

    Remember, @[x] is a literal expression defining an NSArray containing x


    So a line like this:

    [_mutableCountViewArray addObject:@[self.a.view]];
    

    should become:

    [_mutableCountViewArray addObject:self.a.view];
    

    (of course, this applies to every object you add in the next few lines...)


    Also, as a sidenote:

    _countViewArray = [[NSArray alloc] init];
    

    in your first snippet is redundant since you reassign a value in the next line...