【发布时间】:2015-10-02 16:35:04
【问题描述】:
我在 UITableViewCell 中添加了 UISwitch,但是 当开关打开/关闭时如何从数组中添加或删除对象。
这是我在 cellForRowAtIndexPath 中的代码:
if (indexPath.section == 0)
{
cell.textLabel.text = [menuArray1 objectAtIndex:indexPath.row];
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
if ([userSession.searchedArray count] > 0)
{
if ([userSession.searchedArray containsObject:cell.textLabel.text])
{
switchview.on = YES;
}
}
switchview.tag = indexPath.row;
[switchview addTarget:self action:@selector(switchToggle:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = switchview;
}
//Switch action
-(void)switchToggle:(id)sender
{
UISwitch *theSwitch = (UISwitch *)sender;
NSLog(@"tag %d",theSwitch.tag);
NSInteger i = [sender tag];
if (theSwitch.isOn)
{
NSString *str = [menuArray1 objectAtIndex:i];
[array addObject:str];
userSession.searchedArray = array;
NSLog(@"SearchArray %@",userSession.searchedArray);
}
else
{
[array removeObjectAtIndex:i];
userSession.searchedArray = array;
}
}
当我在 UISwitch 关闭时尝试从数组中删除对象时,我的 应用程序正在崩溃。
我哪里出错了?如果 UISwitch 处于打开/关闭状态,请建议我在数组中添加或删除对象的正确方法。
提前致谢
【问题讨论】:
-
什么是崩溃信息?
-
当您从数组中添加和删除对象时,请勿使用 removeObjectAtIndex: 直到您确定该对象是否存在于该索引处并且是您尝试删除的正确对象
-
听起来像 array-out-of-bounce 崩溃...
标签: ios objective-c iphone nsmutablearray uiswitch