开发者

array position objective-c

I have an NSArray. Lets say that i have 3 objects inside it. e.g

test (
        {
        Code = A;
        Comment = "None ";
        Core = Core;
},{
        Code = B;
        Comment = "None ";
        Core = Core;
},{
        Code = C;
        Comm开发者_JAVA百科ent = "None ";
        Core = Core;
})

I want to search for a 'Code' and return the array index. How can i do this? e.g. locate code 'b' and i would have '1' being returned (since its the second position within the array).


Off the top of my head so there might be some typos in it. I am assuming the objects inside your array are dictionaries:

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

You could also use (probably more efficient)

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

passing a predicate of @"Code == 'B'" on the block. This method will specifically return the index of objects passing the test.


If targeting iOS 4.0 or above there are NSArray methods that allow you to do this using blocks.

– indexOfObjectPassingTest:
– indexesOfObjectsPassingTest:
etc..

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);


In its simplest form I would use the following:

- (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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜