1

我是 Objective C 的新手。在我的应用程序中,我有一组数据,其中我只需要正数并且需要删除负数。

result = [NSMutableArray arrayWithObjects: @"1",@"2",@"3","-4","-5","6","9",nil];
NSLog(@"  Before Remove  %d", [result count]);
NSString *nullStr = @"-";
[result removeObject:nullStr];

如何做到这一点?任何指针?

4

5 回答 5

6

您可以使用谓词来过滤数组

NSArray * numbers = @[@"1", @"2", @"3", @"-4", @"-5", @"6", @"9"];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"integerValue >= 0"];
NSArray * positiveNumbers = [numbers filteredArrayUsingPredicate:predicate];

结果

[@"1", @"2", @"6", @"9"]

另请注意,这将适用于NSNumbers 数组和 s 数组NSString,因为它们都具有该integerValue方法。

于 2013-08-21T10:26:23.637 回答
2

你写的是一个字符串数组,如果没关系,你可以循环数组并删除以 - 开头的字符串

由于在迭代时无法删除对象,因此可以创建一个新数组并仅存储正数(或标记要删除的项目并在循环后删除)

NSMutableArray onlyPositives = [[NSMutableArray alloc] init]
for(int i=0; i < [result count]; i++)
{
    if(![result[i] hasPrefix:@"-"])
        [onlyPositives add:[result[i]]
}
于 2013-08-21T09:46:43.950 回答
0

If you have an array and you want to filter items out of it, then using an NSPredicate is a good way to do it.

You haven't said whether your array contains NSNumbers or NSStrings, so here's a demonstration of how to use predicates to filter an array in both cases

// Setup test arrays
NSArray *stringArray = @[@"-1", @"0", @"1", @"2", @"-3", @"15"];
NSArray *numberArray = @[@(-1), @0, @1, @2, @(-3), @15];

// Create the predicates 
NSPredicate *stringPredicate = [NSPredicate predicateWithFormat:@"integerValue >= 0"];
NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF >= 0"];

// Filtering the original array returns a new filtered array
NSArray *filteredStringArray = [stringArray filteredArrayUsingPredicate:stringPredicate];
NSArray *filteredNumberArray = [numberArray filteredArrayUsingPredicate:numberPredicate];

// Just to see the results, lets log the filtered arrays.
NSLog(@"New strings %@", filteredStringArray); // 0, 1, 2, 15
NSLog(@"New strings %@", filteredNumberArray); // 0, 1, 2, 15

This should get you started.

于 2013-08-21T10:17:43.177 回答
0
NSIndexSet *indexesOfNegativeNumbers = [result indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    return [(NSString *)obj hasPrefix:@"-"];
}];

[result removeObjectsAtIndexes:indexesOfNegativeNumbers];
于 2013-08-21T10:07:17.257 回答
0

尝试这个:

for(NSString *number in [result copy])
{
    if([number intValue] < 0)
    {
         [result removeObject:number];
    }
}
于 2013-08-21T10:00:35.710 回答