[英]Checking for 0 as an integer value from elements of a NSMutableArray
我有一个NSMutable数组,其中插入了这样的元素:
[availableSeatsArray addObject:[NSString stringWithString:num_available]];
我想删除数组中值为零或更低的元素。 我尝试使用其int值甚至是字符串值来检查该元素的值,但是它始终通过'0'元素大小写。 下面的前后控制台的阵列输出。
for (int i=0;i<[availableSeatsArray count]; i++) {
if ([[availableSeatsArray objectAtIndex:i] intValue] <= 0 || ([[availableSeatsArray objectAtIndex:i] isEqualToString:@"0"])) {
NSLog(@"Removed index: %d", [[availableSeatsArray objectAtIndex:i] intValue]);
[availableSeatsArray removeObjectAtIndex:i];
}
}
控制台输出:
Available array: (
"-2",
10,
5,
"-5",
0,
10,
10,
)
2012-08-14 11:13:28:002 -[dmbAddReservation viewWillAppear:] [Line 1074] Removed index: -2
2012-08-14 11:13:28:004 -[dmbAddReservation viewWillAppear:] [Line 1074] Removed index: -5
2012-08-14 11:13:28:006 -[dmbAddReservation viewWillAppear:] [Line 1083] Available array: (
10,
5,
0, // I cannot explain why this element was not removed
10,
10,
)
有两点。
integerValue
而不是intValue
NSNumber
。 那就是它的目的。 因此,您可以使用以下命令创建数组:
[availableSeatsArray addObject:[NSNumber numberWithInteger:[num_available integerValue]]];
然后您可以将它们过滤掉(请注意,我正在使用基于块的枚举方法):
__block NSMutableArray *itemsToRemove;
[availableSetsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj integerValue] == 0]) {
[itemsToRemove addObject:obj]
}
}];
// Now that you've selected which objects to remove you can actually remove them.
[availableSetsArray removeObjectsInArray:itemsToRemove];
它正在跳过该元素,因为您要删除-5之前的元素。 i
递增到下一个值,并且该索引现在被前10个占据。可能有几种解决方法,但是想到的第一个方法是filteredArrayUsingPredicate:
请参阅NSArray文档 )。
问题在于这种方法使用了根本上有缺陷的逻辑。 错误地不会删除连续出现的0或否定对象。 原因是,在for循环中检查“ -5”时,它通过了测试,然后将其删除,缩小数组并移动其剩余元素,以便现在将“ 0”替换为“ -5”。 “ -5”。 但是在for循环中,无论元素是否被删除,都可以前进循环变量(在本例中为i),因此现在“ i”指向零后的一。 而且不会被检查。 解决方案:仅当没有连续的元素通过测试时才增加循环变量(即,将if更改为while):
for (int i = 0; i < [availableSeatsArray count]; i++) {
while ([[availableSeatsArray objectAtIndex:i] intValue] <= 0
|| ([[reservatiomAvailableArray objectAtIndex:i] isEqualToString:@"0"])) {
NSLog(@"Removed index: %d", [[availableSeatsArray objectAtIndex:i] intValue]);
[availableSeatsArray removeObjectAtIndex:i];
}
}
我会去NSPredicate
和predicateWithBlock:
NSPredicate
对于NSMutableArray,您可以使用filterUsingPredicate:
方法,该方法将从阵列中删除不需要的对象,而无需创建新的对象。 下面的代码可以做到这一点:
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"0",@"1",@"2", @"-50", nil];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSString* evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject compare:@"0" options:NSNumericSearch] > 0;
}];
[arr filterUsingPredicate:predicate];
NSLog(@"%@", arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.