[英]NSMutableArray Initialization at multiple indexes
Trying to create an array to store data about a deck of cards. 尝试创建一个数组来存储有关一副纸牌的数据。 I'm wanting to keep a boolean for each card.
我想为每张卡保留布尔值。
I want to create an array of capacity 52 with each index initialized to NO (or 0). 我想创建一个容量为52的数组,每个索引都初始化为NO(或0)。 Is there a way to do this all in one go instead of
有没有办法一次性完成所有操作
[[NSArray alloc] initWithObjects: 0, 0, 0, .... nil];
Either put all 52 instances of @NO
as parameters to initWithObject:
or create it as an NSMutableArray
and use a loop to add 52 objects. 将
@NO
所有52个实例作为参数放入initWithObject:
或将其创建为NSMutableArray
并使用循环添加52个对象。
NSMutableArray *array = [NSMutableArray arrayWithCapacity:52];
for (int i = 0; i < 52; i++) {
[array addObject:@NO];
}
BTW - passing a set of 0
to initWithObjects:
won't work at all. 顺便说一句-将一组
0
传递给initWithObjects:
根本不起作用。 Either use @NO
for the BOOL
value of NO
or use @0
for the number 0
(wrapped as an NSNumber
). 将
@NO
用作BOOL
的NO
值,或者将@0
用作数字0
(包装为NSNumber
)。 Just using 0
is the same as nil
so no objects will be added. 仅使用
0
与nil
相同,因此不会添加任何对象。
Use a loop 使用循环
NSMutableArray *deck = [NSMutableArray array];
for(NSInteger i = 0; i < 52; i++)
{
[deck addObject:[NSNumber numberWithInteger:0]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.