【问题标题】:Update Custom Object within Array using a key [duplicate]使用键更新数组中的自定义对象[重复]
【发布时间】:2015-12-19 08:23:28
【问题描述】:

标题可能有点不清楚。但这是我想要实现的目标:

我有一个带有自定义对象的NSMutableArray,例如

[
Custom Object 1,
Custom Object 2,
Custom Object 3,
..
..
..
Custom Object 10
]

Custom object 由以下变量组成:

id, name, date, seen_count;

我的值为id,例如10

现在我想要在NSMutableArray 中获取custom object 中的Index,以便我可以更新该对象并在UITableView 中重新加载特定的Row/Cell 以反映更改。

P.S: 一种方法是遍历数组。但是还有其他方法可以实现吗?

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    使用 NSPredicate::

    CustomObject *object= [[[yourArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"id == 10"]] lastObject];
    
    // make changes in object.
    

    获取数组中对象的索引::

    NSUInteger positionOfChange =  [yourArray indexOfObject:object];
    
    // update your cell that is on position positionOfChange integer value
    

    希望这会有所帮助,对于代码 sn-p 中的任何错字,我们深表歉意。

    注意:: 如果您不确认对象将始终存在于 id 中,则首先检查过滤后的数组是否具有对象,然后再进一步,否则它将崩溃。 如果不确定,请不要检查 filteredArrayUsingPredicate 中的 lastobject。

    【讨论】:

      【解决方案2】:

      由于数组只能通过索引访问,因此遍历数组是唯一的方法。您可以显式循环,寻找合适的对象或隐式使用NSArrayindexOfObjectPassingTest 方法。这种方法的优点是它只需要迭代到第一个匹配,而filteredArrayUsingPredicate 需要迭代整个数组。

      NSInteger objectIndex=[myArray indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          CustomObject *myObject=(CustomObject *)obj;
          if (obj.id==targetid) {   // Assumes id is an int, change the test as appropriate if it is a string or other object
              *stop=YES;
          }
      }];
      

      另一种方法是使用存储对象索引的辅助 NSDictionary。这需要数组的单次迭代来构建字典,但允许您更快地定位给定对象。

      为方便起见,我假设在这种情况下 id 是一个字符串;如果它是一个 int 那么你需要把它装在一个 NSNumber 中:

      NSMutableDictionary auxDict=[NSMutableDictionary new];
      for (i=0;i<myArray.count;i++) {  
         CustomObject *obj=myArray[i];
         [auxDict addObject:[NSNumber numberWithInt:i] forKey:obj.id];
      }
      

      然后,要访问一个对象,只需使用字典

      NSNumber *indexNumber=auxDict[targetId];
      int index=[indexNumber intValue];
      CustomObject *object=myArray[index];
      

      【讨论】:

        【解决方案3】:
            NSString *search=@"5";
            NSInteger index=-1;
            if ([[arr valueForKey:@"id"] containsObject:search]) {
                index=[arr1 indexOfObject:search];
        
            }
            if (index!=-1) {
                //do whatever with your index
            }
        

        【讨论】:

        • 您介意解释一下您的答案吗?
        • 这是一个相当低效的解决方案 - 首先它创建一个新数组,其中包含第一个数组中对象的 id 属性的值,然后检查所需的 id在这个新数组中(迭代过程中的数组),然后它获得匹配对象的索引(再次迭代数组)使其成为 O3n。您可以简单地使用 indexOfObject 开始并检查特殊结果 NSNotFound 而不是使用 containsObject 但这仍然会使其成为 O2n
        • 您可以简单地通过创建新数组来完成。这也将使其成为 O2n。
        猜你喜欢
        • 2020-02-04
        • 1970-01-01
        • 2018-08-23
        • 2018-03-04
        • 1970-01-01
        • 2015-05-12
        • 2014-11-14
        • 2018-09-18
        • 1970-01-01
        相关资源
        最近更新 更多