Как получить индекс в NSArray?

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

NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];

В приведенном выше массиве 1-й объект, 2-й объект, 3-й объект, 4-й объект, 5-й объект, имеющий значение, содержимое, вывод в каждом индексе.

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

}

Вышеупомянутый словарь находится в цикле for, и пары ключ-значение будут добавлены 5 раз (счетчик Somearray). Теперь массив имеет в

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

Сейчас у меня NSString*string = @"1.5";

Теперь мне нужен индекс, в котором val имеет значение 1,5. Как отправить строку в массив, чтобы найти индекс.

Может кто-нибудь поделиться кодом, пожалуйста.

Заранее спасибо.


person Univer    schedule 11.11.2011    source источник


Ответы (3)


Используйте метод indexOfObject

int inx= [array indexOfObject:@"1.5"];

Для поиска определенного ключевого значения индекса.

int inx;
for (int i=0; i<[array count]; i++) {
    if ([[[array objectAtIndex:i] allKeys] containsObject:@"val"]) {
        inx=i;
         break; 
    }
}
person mandeep-dhiman    schedule 11.11.2011
comment
Массив содержит словари, а не строки. Он хочет найти индекс словаря, ключ val которого имеет значение, содержащее 1,5. Этот ответ не сделает этого. - person rob mayoff; 12.11.2011

Метод, который вы ищете, это -[NSArray indexOfObjectPassingTest:]. Вы бы использовали это так:

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

Если вы просто хотите проверить, что val начинается с «1.5», вы должны использовать вместо этого hasPrefix:.

person rob mayoff    schedule 11.11.2011
comment
[[id objectForKey:@"val"] hasPrefix:@"1.5"] Проверьте Справочник по классу NSString. - person rob mayoff; 12.11.2011

Попробуй это -

NSArray *valArray = [array valueForKey:@"val"];
int index = [valArray indexOfObject:@"1.5"]; 

Приложенный ответ, данный Mandeep, чтобы показать вам магию кодирования значения ключа;)

person Devarshi    schedule 12.11.2011