2011-11-11 45 views
2
NSMutableArray*array = [[NSMutableArray alloc]init]; 

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

在上述陣列第一對象,2ndObject,第三對象,第四對象,具有VAL,內容,結束在每個索引第五對象。如何獲取NSArray中的索引?

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是具有it.How 1.5至在發送給STR陣列找到的索引的索引。

任何人都可以共享代碼,請。

在此先感謝。

回答

2
NSUInteger idx = UINT_MAX; 
    NSCharacterSet* spaceSet = [NSCharacterSet whitespaceCharacterSet]; 
    for(int i=0,i_l=[Yourarray count];i<i_l;i++) { 
     NSString* s_prime = [[Yourarray objectAtIndex:i] valueForKey:@"val"]; 
     if ([s_prime length] < 4) { 
      continue; 
     } 
     NSString *subString = [[s_prime substringToIndex:4] stringByTrimmingCharactersInSet:spaceSet]; 
     // NSLog(@"index %@",s); 
     if ([subString isEqualToString:secretNumber]){ 
      idx = i; 
      break; 
     } 
    } 
    if (idx != UINT_MAX) { 
     // NSLog(@"Found at index: %d",idx); 
    } else { 
    // NSLog(@"Not found"); 
    } 
6

你正在尋找的方法是-[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:代替。

+0

如何使用有前綴的方法 – Univer

+0

'[ id objectForKey:@「val」] hasPrefix:@「1.5」]'檢查* [NSString類參考](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class /Reference/NSString.html#//apple_ref/occ/instm/NS字符串/ hasPrefix:)*。 –

12

使用方法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; 
    } 
} 
+0

好又簡單 –

+0

+1 from me ... cheetey;) – Devarshi

+0

該數組包含字典,而不是字符串。他想找到其「val」鍵值爲「1.5」的字典的索引。這個答案不會那樣做。 –

6

試試這個 -

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

由Mandeep給,給你看鍵值編碼的魔法追加的答案;)