NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:@"3",@"1", @"2",@"0", @"0", @"1",@"3",@"1", @"2",@"0", @"0", @"1", nil];
现在如何使用具有对象1的所有索引创建一个Array1。对于这种情况,它将有1,5,7和11作为其元素?
答案 0 :(得分:0)
您必须使用if
条件来检查每个对象的值,然后将对象的索引存储在数组中。
答案 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);