【问题标题】:NSMutableArray check if item exists [duplicate]NSMutableArray检查项目是否存在[重复]
【发布时间】:2013-08-16 14:10:30
【问题描述】:

我有一个包含 100 多个字符的 NSMutableArray,我在其中填充了一个表格:

int rowCount = indexPath.row;
Character *character = [self.characterArray objectAtIndex:rowCount];

cell.textLabel.text = character.name;
cell.detailTextLabel.text = character._id;

然后我得到了一个单独的 NSMutableArray,其中包含一个 _id 和邻居值,但是这个数组只有大约 8 个带有随机 id 的值。

基本上我想检查第二个数组中是否存在character._id,它会在表格上显示一个复选标记。

我已经尝试过:

Neighbour *neighbour = [self.neighbourArray objectAtIndex:rowCount];

if (character._id == neighbour._id && neighbour.neighbour == 1){
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
         cell.accessoryType = None;
}

但它会使应用程序崩溃(因为它只有 8 个值 100,我猜)

有没有简单的方法或更好的方法来彻底检查?

谢谢,任何有建设性的建议将不胜感激,我是 Xcode 的新手。

【问题讨论】:

    标签: objective-c nsmutablearray


    【解决方案1】:

    你可以使用KVC来避免枚举:

    BOOL result = [[neighbours valueForKey:@"_id"] containsObject: character._id];
    

    【讨论】:

    • 非常优雅的解决方案。
    • 谢谢,一切都解决了。
    【解决方案2】:

    目前您正在检查 Neighbour 同一索引处的 Character 对象,您应该在整个数组中检查它,

    你可以这样试试

    -(BOOL)check :(Character *) character
    {
    
    for(Neighbour *neighbour in  self.neighbourArray )
    {
      if(character._id == neighbour._id && neighbour.neighbour == 1)
       return TRUE;
    }
    
      return FALSE;
    

    }

    现在只需在 tableviewMethod 中调用此方法

    int rowCount = indexPath.row;
    Character *character = [self.characterArray objectAtIndex:rowCount];
    
    if ([self check:character]){
             cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
             cell.accessoryType = None;
    }
    

    【讨论】:

    • 我试了一下,但在第一个块上出现“控制可能到达非无效函数的结尾”错误,我猜是因为它没有给出明确的回报。
    • 是的,请检查更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2020-07-20
    • 2012-03-31
    相关资源
    最近更新 更多