Ios 如何在iPhone中使用UISwitch on/off添加/删除阵列中的对象
我在UITableViewCell中添加了UISwitch,但是如何在开关打开/关闭时从数组中添加或删除对象。 这是我在CellForRowatineXpath中的代码:Ios 如何在iPhone中使用UISwitch on/off添加/删除阵列中的对象,ios,objective-c,iphone,nsmutablearray,uiswitch,Ios,Objective C,Iphone,Nsmutablearray,Uiswitch,我在UITableViewCell中添加了UISwitch,但是如何在开关打开/关闭时从数组中添加或删除对象。 这是我在CellForRowatineXpath中的代码: if (indexPath.section == 0) { cell.textLabel.text = [menuArray1 objectAtIndex:indexPath.row]; UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZ
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处于打开/关闭状态,请建议我从阵列中添加或删除对象的正确方法
提前感谢hii首先检查对象是否已添加 添加对象后记录数组
[array removeObject: [menuArray1 objectAtIndex:i]];
尝试此操作。hii首先检查对象是否已添加 添加对象后记录数组
[array removeObject: [menuArray1 objectAtIndex:i]];
试试这个。什么是崩溃消息?当您从数组中添加和删除对象时,不要使用removeObjectAtIndex:除非您确定该对象是否存在于该索引中,并且是您正试图移除的正确对象,就像从反弹崩溃中移除数组一样…崩溃消息是什么?当您从数组中添加和移除对象时,不要使用removeObjectAtIndex:除非您确定该索引中是否存在该对象,并且该对象是您尝试移除的正确对象,就像反弹崩溃中的数组一样。。。