NSMutableArray 中的對象是這樣: “0,1,0,1,1,1,0,0”
然後我要獲取所有值為“ 1 ”的對象的索引。
for (NSString *substr in activeItems){
if ([substr isEqualToString:@"1"]){
NSLog(@"%u",[activeItems indexOfObject:substr]);
}
}
但是根據文檔說明中方法indexOfObject
是返回最低索引值,那麼我應該怎麼獲取值為 “1” 的對象索引呢?
這個可以通過設置range來解決.
NSRange range = NSMakeRange(0, activeItems.count);
for (NSString *substr in activeItems)
{
if ([substr isEqualToString:@"1"])
{
NSInteger index = [activeItems indexOfObject:substr inRange:range];
NSLog(@"the object indix is: %d", index);
range.location = ++index;
range.length = activeItems.count - index;
}
}
當然,這種對collection的過濾操作,我建議用NSPredicate.不過你這個過濾也不算復雜,怎樣都行.
不過我還是給你寫出來方法.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '1'"];
NSArray *resAry = [activeItems filteredArrayUsingPredicate:predicate];
NSRange range = NSMakeRange(0, activeItems.count);
for (NSString *substr in resAry)
{
NSInteger index = [activeItems indexOfObject:substr inRange:range];
NSLog(@"the object indix is: %d", index);
range.location = ++index;
range.length = activeItems.count - index;
}