我是一个完全的菜鸟,需要帮助我正在编写的方法。
该方法创建一副牌(使用NSMutableArray)。我首先尝试随机加载数组1-13(每个数字出现一次)。
当我运行一个简单的测试程序来打印数组中的值时,我得到一个“Build Successful”但程序启动时出错。错误说“[__NSArrayM insertObject:atIndex:]:object不能为nil”。
一旦我理解了我做错了什么,我就可以正确地扩展这个方法。谢谢!
注意:这是我的第一篇文章。这类问题好吗?
- (void) createDeck {
int r;
BOOL same;
deck = [[NSMutableArray alloc]init];
NSNumber *randNum;// = nil;
randNum = [[NSNumber alloc]init];
[randNum initWithInt: (arc4random()%13)+1];
[deck addObject: randNum]; // First card added to deck
same = FALSE;
while (!same) {
for (int i=1; i<13; i++) {
same = FALSE;
for (r=0; r<=i; r++) {
[randNum initWithInt: (arc4random()%13)+1];
if ([deck objectAtIndex:r] == [deck objectAtIndex:i]) {
same = TRUE;
}
[deck addObject: randNum]; // Next card added to deck
}
}
}
}
答案 0 :(得分:3)
你无法重新启动randNum:
NSNumber *randNum;// = nil;
randNum = [[NSNumber alloc]init];
[randNum initWithInt: (arc4random()%13)+1];
并且第三行无论如何都错过了作业。只是做:
NSNumber *randNum = [[NSNumber alloc] initWithInt:(arc4random()%13)+1];
并将其放在内部for循环中,如下所示:
BOOL same = FALSE;
NSMutableArray *deck = [[NSMutableArray alloc] initWithCapacity:13];
[deck addObject:[[NSNumber alloc] initWithInt:(arc4random()%13)+1]]; // First card added to deck
while (!same) {
for (int i = 1; i < 13; i++) {
same = FALSE;
for (int r = 0; r <= i; r++) {
NSNumber *randNum = [randNum initWithInt:(arc4random()%13)+1]; // modern ObjC will assign a register for this outside the while loop, but restrict the variable's scope to the inner-most loop
if ([deck objectAtIndex:r] == [deck objectAtIndex:i])
same = TRUE;
[deck addObject: randNum]; // Next card added to deck
}
}
请注意,我没有想过你在这里尝试做什么的逻辑,我只试图解析NULL
对象引用。该错误指的是循环外的第一行[deck addObject: randNum]
。
答案 1 :(得分:0)
尝试在使用NSNumber
NSNumber * randNum = [NSNumber numberWithInt: (arc4random%13)+1];
而不是
[[NSNumber alloc] initWithInt: ]