使用服务器连接崩溃我的iOS游戏

时间:2013-05-31 14:10:41

标签: ios cocos2d-iphone asihttprequest

我在我的应用上遇到了一些问题:当你玩游戏时,时间结束,服务器会发送你所做的分数。当互联网关闭时,应用程序仍会发送请求,当互联网再次启动时,应用程序崩溃。控制台告诉我这个:

2013-05-31 11:00:34.376 xxxxxxx [1721:1be03] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(0x3352012 0x2754e7e 0x32f40b4 0xad260 0xacc1b 0xacb95 0xa770c 0x29ce3 0xa743b 0x68e04 0x68b0b 0x874b8 0x27686b0 0x1e1f765 0x32d5f3f 0x32d596f 0x32f8734 0x32f7f44 0x32f7e1b 0x358a7e3 0x358a668 0x1323ffc 0x65a9a 0x28e5 0x1)
libc++abi.dylib: terminate called throwing an exception

有人可以告诉我出了什么问题吗?

修改

我放了一个异常断点,发现问题的起源就在这里。这是服务器响应的解析,用管道分隔:

-(void)parseNextGameScoresStatWithResponse:(NSString *)response{
    /*Response
     Position|username|totalscore|country|
     */
    if(response.length == 0 )
        return;

    NSString * cuttedString = [response substringFromIndex:1];

    NSMutableArray *responsesArray = [NSMutableArray arrayWithArray:[cuttedString componentsSeparatedByString:@"|"]];

    if(responsesArray.count != 0)
       [responsesArray removeLastObject];
    else{
        return;
    }

  //  NSLog(@"responsesArray = %@", responsesArray);

    self.statsArray = [NSMutableArray arrayWithCapacity:0];

    for (int i = 0; i < [responsesArray count]-1; i+=4) {
        StatModel *stat = [[StatModel alloc] init];
        stat.position = [[responsesArray objectAtIndex:i] intValue];
        stat.userName = [responsesArray objectAtIndex:i+1];
        stat.totalScore = [[responsesArray objectAtIndex:i+2] intValue];
        stat.countryCode = [responsesArray objectAtIndex:i+3];
  //      NSLog(@"stat of next game scores = %d %@ %d %@",stat.position, stat.userName, stat.totalScore, stat.countryCode);
        [self.statsArray addObject:stat];
        [stat release];
    }
}

1 个答案:

答案 0 :(得分:2)

问题在于,即使[responseArray count]0,它仍会进入for循环。

从以下位置更改循环:

for (int i = 0; i < [responsesArray count]-1; i+=4) {
  ..

要:

int i = 0;
while (i < [responsesArray count]) {
    StatModel *stat = [[StatModel alloc] init];
    stat.position = [[responsesArray objectAtIndex:i++] intValue];
    stat.userName = [responsesArray objectAtIndex:i++];
    stat.totalScore = [[responsesArray objectAtIndex:i++] intValue];
    stat.countryCode = [responsesArray objectAtIndex:i++];
    [self.statsArray addObject:stat];
    [stat release];
}