NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger index = [myArray indexOfObject:num];
NSLog(@"%ld", index); // 輸出 9223372036854775807 (NSNotFound)
陣列明明包含 56,卻返回 NSNotFound。
indexOfObject: 使用 **isEqual:** 比較對象,而非指針地址。NSNumber 的 isEqual: 比較**數值**與**類型**。若陣列元素是 int (基本類型) 或不同數值類型 (如 @56 vs @56L),可能不相等。NSString @"56",而查找用 NSNumber,類型不同 isEqual: 返回 NO。
// 1. 打印陣列真實內容
NSLog(@"Array: %@", myArray);
// 輸出示例:(@"56", @"57", @"58") → 全是 NSString
// 2. 統一查找類型
NSString *strNum = [NSString stringWithFormat:@"%d", 56];
NSInteger index = [myArray indexOfObject:strNum]; // 找到
// 3. 或遍歷手動比較(靈活處理類型差異)
NSInteger foundIndex = NSNotFound;
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSNumber class]] && [(NSNumber *)obj intValue] == 56) {
foundIndex = idx;
*stop = YES;
} else if ([obj isKindOfClass:[NSString class]] && [obj intValue] == 56) {
foundIndex = idx;
*stop = YES;
}
}];
indexOfObject: 依賴 isEqual:,**類型必須一致**。NSNotFound 定義為 NSIntegerMax (9223372036854775807),非負數視為有效索引。
let array: [Any] = [56, "57", 58] // 混合類型
if let index = array.firstIndex(where: { ($0 as? Int) == 56 || ($0 as? String) == "56" }) {
print("Found at \(index)")
} else {
print("Not found")
}
indexOfObject: 返回 NSNotFound 通常因**查找對象類型與陣列元素類型不匹配**導致 isEqual: 失敗。解決:打印陣列確認類型 → 構造同類型查找對象,或用遍歷塊手動比較數值。