1

我正在尝试将我从 NSURL 获得的数组添加到使用 for 循环的数组中:

(int i = 0; i < 10; i++) 

使其成为二维数组。不断收到 NSRangeException 错误。它只能在 index[0] 处插入对象或添加对象,当 'i' 增加到 1 时,它会引发错误。它只能意味着它不是添加而是覆盖,所以当它第二次覆盖并且 i = 1 时,它会抛出错误。如何添加更多而不是覆盖初始化的二维数组?

- (void)qBlock{
    for (int i = 0; i < 10; i++) {
        NSURL *url = [NSURL URLWithString:@"http://somefiles.php"];
        NSError *error;
        NSStringEncoding encoding;
        NSString *response = [[NSString alloc] initWithContentsOfURL:url 
                                                        usedEncoding:&encoding 
                                                               error:&error];
        if (response) {

            const char *convert = [response UTF8String];
            NSString *responseString = [NSString stringWithUTF8String:convert];
            NSMutableArray *sample = [responseString JSONValue];

            block = [[NSMutableArray alloc]init];
        [block insertObject:sample atIndex:i];
        }


    else {
        UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"ALERT" message:@"Internet Connection cannot be established." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert1 show];
    }
}
//Calling 10 blocks of codes
for (id obj in block) {
    NSLog(@"%@",obj);
}
4

1 回答 1

1

这:

        block = [[NSMutableArray alloc]init];
    [block insertObject:sample atIndex:i];

在通过 for 循环的每次迭代中,将整个块数组替换为一个空数组。

将块数组初始化移到 for 循环之外。

于 2012-05-03T20:25:04.667 回答