【问题标题】:array position objective-c阵列位置objective-c
【发布时间】:2011-09-27 19:36:35
【问题描述】:

我有一个 NSArray。可以说我里面有 3 个对象。例如

test (
        {
        Code = A;
        Comment = "None ";
        Core = Core;
},{
        Code = B;
        Comment = "None ";
        Core = Core;
},{
        Code = C;
        Comment = "None ";
        Core = Core;
})

我想搜索“代码”并返回数组索引。我怎样才能做到这一点?例如定位代码“b”,我将返回“1”(因为它是数组中的第二个位置)。

【问题讨论】:

    标签: objective-c xcode ios4 nsarray


    【解决方案1】:

    在我的脑海中,所以可能有一些错别字。我假设你的数组中的对象是字典:

    for (NSDictionary dict in testArray)
    {
        if ([[dict objectForKey:"Code"] isEqualToString:@"B"]
        {
            NSLog (@"Index of object is %@", [testArray indexOfObject:dict]);
        }
    }
    

    你也可以使用(可能更有效)

    - (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
    

    在块上传递@"Code == 'B'" 的谓词。该方法将专门返回通过测试的对象的索引。

    【讨论】:

      【解决方案2】:

      如果面向 iOS 4.0 或更高版本,则有 NSArray 方法允许您使用块来执行此操作。

      – indexOfObjectPassingTest:
      – indexesOfObjectsPassingTest:
      等等。

      NSArray *test = [NSArray arrayWithObjects:
                       [NSDictionary dictionaryWithObjectsAndKeys:@"A", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"B", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
                       [NSDictionary dictionaryWithObjectsAndKeys:@"C", @"Code", @"None", @"Comment", @"Core", @"Core", nil],
                       nil];
      NSIndexSet *indexes =[test indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
          return [[obj valueForKey:@"Code"] isEqualToString:@"B"];
      }];
      
      NSLog(@"Indexes with Code B: %@", indexes);
      

      【讨论】:

        【解决方案3】:

        在最简单的形式中,我将使用以下内容:

        - (NSInteger)indexForText:(NSString*)text inArray:(NSArray*)array
        {
          NSInteger index;
          [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            YourObject* o = (YourObject*)obj;
            if ([[o property] isEqualToString:text]) {
              index = idx;
              *stop = YES;
            }
          }];
          return index;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多