用NSArray和NSMutableArray填充NSStackView
问题描述:
我有一个堆栈来填充一个视图数组。用NSArray和NSMutableArray填充NSStackView
_countViewArray = [[NSArray alloc] init];
_countViewArray = @[self.a.view,self.b.view,self.c.view];
_stackView = [NSStackView stackViewWithViews:_countViewArray];
它工作的很好。 如果我想用一个可变数组替换这个数组,怎么办?
我尝试此代码为“动态”堆栈视图中,并最终转换成可变数组简单数组,但不工作:
_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];
在consolle如果我打印可变数组我有:
(
(
"<NSView: 0x600000121ea0>"
),
(
"<NSView: 0x600000120780>"
,
(
"<NSView: 0x60000a0>"
)
)
我该如何解决?
答
的问题是,要添加阵列(包含单个视图)而不是视图...
记住,@[x]
是文本表达式限定包含x
因此,一个线的NSArray
像这样:
[_mutableCountViewArray addObject:@[self.a.view]];
应该变成:
[_mutableCountViewArray addObject:self.a.view];
(当然,这也适用于每一个对象,你在接下来的几行添加...)
此外,作为一个旁注:
_countViewArray = [[NSArray alloc] init];
在你的第一个片段是多余的,因为你在下一行重新分配一个值...
嘿,谢谢!我不明白多余的感觉。第一个代码块没有可变数组,第二个数组的alloc被理解... – Joannes
@alfioal我的意思是说你可以安全地删除这行'_countViewArray = [[NSArray alloc] init];'(在你使用的情况下第一个片段),因为您在下一行再次为'_countViewArray'指定了一个不同的值......我希望这是有道理的:) – Alladinian
啊,好的!我明白! – Joannes