【问题标题】:How to add/remove objects in array using UISwitch on/off in iPhone如何在 iPhone 中使用 UISwitch on/off 添加/删除数组中的对象
【发布时间】: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


【解决方案1】:

首先检查对象是否被添加。

添加对象后记录数组。

 [array removeObject: [menuArray1 objectAtIndex:i]];

试试这个。

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 2021-02-25
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 2017-04-08
    • 2020-05-23
    相关资源
    最近更新 更多