[英]How to get index in an NSArray?
NSMutableArray*array = [[NSMutableArray alloc]init];
NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
在上面的數組中,第一對象,第二對象,第三對象,第四對象,第五對象在每個索引中具有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];
}
上面的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];
現在我有NSString*string = @"1.5";
現在我需要val中有1.5的索引。如何將str發送到數組以查找索引。
任何人都可以共享代碼。
提前致謝。
使用方法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;
}
}
您正在尋找的方法是-[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:
而不是。
嘗試這個 -
NSArray *valArray = [array valueForKey:@"val"];
int index = [valArray indexOfObject:@"1.5"];
Mandeep給出的附加答案,向您展示鍵值編碼的魔力;)
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.