我在 NSMutableArray 中添加 NSInteger 物件作為 NSNumber。但現在我處于這樣的狀態,我需要檢查一個 NSInteger 是否在 NSMutableArray 中。如果陣列包含該值,那么我將執行我的下一個代碼,否則我將執行其他代碼。只有當陣列不包含該值時,我才想執行 else 條件。我試過這段代碼:
for(int i=0; i<self.indexArray.count; i ){
if([[self.indexArray objectAtIndex:i] integerValue]==self.selectedIndex){
NSLog(@"execute if in the array");
}
else{
NSLog(@"execute if not in the array");
}
}
盡管陣列包含該值,但 else 正在為回圈執行。我的問題是如何檢查一個值是否在 NSMutableArray 中。
uj5u.com熱心網友回復:
這是簡單的解決方案:
BOOL containsSelected = NO;
for (int i = 0; i < self.indexArray.count; i ){
if ([[self.indexArray objectAtIndex:i] integerValue] == self.selectedIndex){
containsSelected = YES;
break;
}
}
if (containsSelected) {
NSLog(@"execute if in the array");
} else {
NSLog(@"execute if not in the array");
}
我相信這可以進一步簡化為:
if ([self.indexArray containsObject:@(self.selectedIndex)]) {
NSLog(@"execute if in the array");
} else {
NSLog(@"execute if not in the array");
}
但我沒有測驗過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456804.html
