如何从包含我选择的对象的数组创建索引数组?

时间:2014-09-05 02:17:36

标签: objective-c arrays indexing nsmutablearray

NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:@"3",@"1", @"2",@"0", @"0", @"1",@"3",@"1", @"2",@"0", @"0", @"1", nil];

现在如何使用具有对象1的所有索引创建一个Array1。对于这种情况,它将有1,5,7和11作为其元素?

3 个答案:

答案 0 :(得分:0)

您必须使用if条件来检查每个对象的值,然后将对象的索引存储在数组中。

请参阅:Search NSArray for value matching value

答案 1 :(得分:0)

您可以在NSMutableArray

上使用indexOfObject:inRange:方法

检查此代码:

   NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:@"3",@"1", @"2",@"0", @"0", @"1",@"3",@"1", @"2",@"0", @"0", @"1", nil];
    NSMutableArray * array1 = [NSMutableArray array];

    NSUInteger loc = 0;
    NSUInteger len = myIdentityArray.count;

    NSRange range = NSMakeRange(loc, len);
    NSUInteger idx = [myIdentityArray indexOfObject:@"1" inRange:range];

    while (idx != NSNotFound) {
        [array1 addObject:[NSNumber numberWithUnsignedInteger:idx]];
        loc = idx +1;
        len = myIdentityArray.count - loc;
        range = NSMakeRange(loc, len);
        idx = [myIdentityArray indexOfObject:@"1" inRange:range];
    }

    NSLog(@"%@",array1);

答案 2 :(得分:0)

通过简单的循环执行此操作:

NSMutableArray *myIdentityArray = @[ @"3", @"1", @"2", @"0", @"0", @"1", @"3", @"1", @"2", @"0", @"0", @"1" ];
NSString *search = @"1";

NSMutableArray *results = [NSMutableArray array];

NSInteger index = 0;
for (NSString *str in myIdentityArray) {
    if ([str isEqualToString:search]) {
        [results addObject:@(index)];
    }
    index++;
}

NSLog(@"results = %@", results);