将整数添加到NSMUtableArray

时间:2012-06-27 12:26:07

标签: iphone ipad nsmutablearray integer uipopovercontroller

我是新的iPad开发者。

我在点击按钮时实现UIPopover,popover包含整数值

当我尝试用整数填充我的数组时,它显示我SIGABRT索引3超出界限我无法看到我的日志,应用程序崩溃。

这是我的代码段:

-(void)btnClick:(id)sender {

    for (int i=3; i<=31; i++) {
        [remindarray addObject:[NSNumber numberWithInteger:i]];
         NSLog(@"no=%@",[remindarray objectAtIndex:i]);
    }

    UIViewController* popoverContent = [[UIViewController alloc]init];
    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(110, 0, 500, 4)];

    popoverTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 250, 665) style:UITableViewStylePlain];
    [popoverTable setDelegate:(id<UITableViewDelegate>)self]; 
    [popoverTable setDataSource:(id<UITableViewDataSource>)self]; 
    [self.view addSubview:popoverTable];
    [popoverTable release];

    [popoverView addSubview:popoverTable];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(250, 600);
    self.popoverController = [[UIPopoverController alloc]
                              initWithContentViewController:popoverContent];

    [self.popoverController  presentPopoverFromRect:CGRectMake(100,0, 535, 35) 
                                             inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];

    [popoverView release];
    [popoverContent release];
}

最后remind array我传递给cellForRowAtIndexPath

代码:

...
cell.textLabel.text=[remindarray objectAtIndex:indexPath.row];
...

5 个答案:

答案 0 :(得分:5)

你的for循环从3开始,所以在数组中以0项开始,然后你插入1项,你尝试在索引3处记录项目,这仍然不在数组中

快速解决方法是

更改

NSLog(@"no=%@",[remindarray objectAtIndex:i]);

NSLog(@"no=%@",[remindarray objectAtIndex:i - 3]);

或者从0开始数组

您还需要更改

cell.textLabel.text=[remindarray objectAtIndex:indexPath.row];

cell.textLabel.text=[NSString stringWithFormat:@"%@", [remindarray objectAtIndex:indexPath.row]];

答案 1 :(得分:2)

因为新创建的数组索引是从0索引而不是从3

开始的

问题出在这个循环中

for (int i=3; i<=31; i++) {
        [remindarray addObject:[NSNumber numberWithInteger:i]];
         NSLog(@"no=%@",[remindarray objectAtIndex:i]);
    }

答案 2 :(得分:1)

for (int i=3; i<=31; i++) {
    [remindarray addObject:[NSNumber numberWithInteger:i]];
     NSLog(@"no=%@",[remindarray objectAtIndex:i]);
}

这里你用3开始我并且你将单个对象分配给remindarray所以首先它只包含一个对象所以objectAtIndex:3将是nil所以修改代码就像这样

NSLog(@"no=%@",[remindarray objectAtIndex:i-3]);

NSLog(@"no=%@",[remindarray objectAtIndex:0]);

答案 3 :(得分:1)

我认为抛出异常的是这一行

NSLog(@"no=%@",[remindarray objectAtIndex:i]);

//
-(void)btnClick:(id)sender {
for (int i=3; i<=31; i++) {
    [remindarray addObject:[NSNumber numberWithInteger:i]];
    //your remindArray has one object, index is 0, but you are accessing the 
    //object which is at the index of 3, but the remindArray
    // has only one object [0]
     NSLog(@"no=%@",[remindarray objectAtIndex:i]);
}

答案 4 :(得分:1)

解决方案很简单:在数组的索引0处添加对象,然后要在索引3处打印对象。 使用:

NSLog(@"no=%@",[remindarray objectAtIndex:i - 3]);