如何在NSArray中获取索引?

Uni*_*ver 2 iphone objective-c ios4 ios

NSMutableArray*array = [[NSMutableArray alloc]init];

NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
Run Code Online (Sandbox Code Playgroud)

在上面的数组中,第一对象,第二对象,第三对象,第四对象,第五对象在每个索引中具有val,内容,结论.

for(int i=0;i<[Somearray count];i++)
{

______________

Here the code is there to give each index ,that is having val,content,conclusion ..

After that  val,content,conclusion in each index will be add to Dict..
____________


NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:val,@"val",content,@"content",conclusion,@"conclusion",nil];

//Each time adding dictionary into array;

[array addObject:Dict];

}
Run Code Online (Sandbox Code Playgroud)

上面的Dictionary是for循环,keyvalue对将被添加5次(Somearray Count).现在有数组

array = [{val="1.1 this is first one",content="This is the content of 0th index",conclusion="this is  the conclusion of 0th index"},{val="1.2 this is first one",content="This is the content of 1st index",conclusion="this is  the conclusion of 1st index"},____,____,______,{val="1.5 this is first one",content="This is the content of 4th index",conclusion="this is  the conclusion of 4th index"},nil];
Run Code Online (Sandbox Code Playgroud)

现在我有 NSString*string = @"1.5";

现在我需要val中有1.5的索引.如何将str发送到数组以查找索引.

任何人都可以共享代码.

提前致谢.

man*_*man 12

使用方法indexOfObject

int inx= [array indexOfObject:@"1.5"];
Run Code Online (Sandbox Code Playgroud)

用于查找索引特定键值.

int inx;
for (int i=0; i<[array count]; i++) {
    if ([[[array objectAtIndex:i] allKeys] containsObject:@"val"]) {
        inx=i;
         break; 
    }
}
Run Code Online (Sandbox Code Playgroud)


rob*_*off 6

你正在寻找的方法是-[NSArray indexOfObjectPassingTest:].你会像这样使用它:

NSUInteger i = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        return [[id objectForKey:@"val"] rangeOfString:@"1.5"].location != NSNotFound;
    }];
Run Code Online (Sandbox Code Playgroud)

如果您只想检查val以"1.5"开头,您可以使用hasPrefix:.


Dev*_*shi 6

试试这个 -

NSArray *valArray = [array valueForKey:@"val"];
int index = [valArray indexOfObject:@"1.5"]; 
Run Code Online (Sandbox Code Playgroud)

Mandeep给出的附加答案,向您展示键值编码的魔力;)