[英]add integer to NSMUtableArray
我是新的iPad开发人员。
我在点击按钮时实现了UIPopover,弹出框包含整数值,
当我尝试用整数填充数组时,它向我显示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];
...
您的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]];
因为新创建的数组索引从0
索引而不是3
问题在这个循环中
for (int i=3; i<=31; i++) {
[remindarray addObject:[NSNumber numberWithInteger:i]];
NSLog(@"no=%@",[remindarray objectAtIndex:i]);
}
for (int i=3; i<=31; i++) {
[remindarray addObject:[NSNumber numberWithInteger:i]];
NSLog(@"no=%@",[remindarray objectAtIndex:i]);
}
在这里,我从3开始,并且正在为单个对象分配提醒数组,因此起初它仅包含一个对象,因此objectAtIndex:3将为nil,因此修改代码如下
NSLog(@"no=%@",[remindarray objectAtIndex:i-3]);
要么
NSLog(@"no=%@",[remindarray objectAtIndex:0]);
我认为抛出异常的是这条线
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]);
}
解决方案很简单:您在数组的索引0处添加一个对象,然后要在索引3处打印该对象。使用:
NSLog(@"no=%@",[remindarray objectAtIndex:i - 3]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.