1

好吧,我遇到了一个 nsarray 问题,它正在从 nsdictionary 添加重复的对象。

情况是这样的:我有一个带有字典数组的 plist 文件。每个字典的键是“codigo”和“var”。

我所做的是检查每个 'var' 值是否 < 0,如果它是 'codigo' 和 'var' 将使用 NSAttributedStrings 获得颜色。

当我遍历数组并将评估的“var”添加到新数组中时,问题就来了。我在最终数组中得到重复的对象。

编辑:解决方案源自 xlc0212 的回答和聊天帮助:

_timer = [NSTimer scheduledTimerWithTimeInterval:0.020 target:self
                                        selector:@selector(time:) userInfo:nil repeats:YES];

NSDictionary *redAttrs    = @{NSForegroundColorAttributeName:[UIColor redColor]};
NSDictionary *greenAttrs  = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.118 green:0.506 blue:0.000 alpha:1.000]};
NSDictionary *orangeAttrs = @{NSForegroundColorAttributeName:[UIColor orangeColor]};

NSString *stringUm = @"";
NSString *stringDois = @"";
NSString *stringTres = @"";


arrayAtivos = [[NSMutableOrderedSet alloc] init];
NSDictionary *item = [[NSDictionary alloc]init];

for (item in array){

    NSString *alfa = [item objectForKey:@"var"];

    float fltNumber = [alfa floatValue];

    if (fltNumber < 0) {
        stringUm = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringUm length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringUm];
        [attStr setAttributes:redAttrs range:NSMakeRange(0,strLength)];

    } else if (fltNumber > 0 ) {
        stringDois = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringDois length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringDois];
        [attStr setAttributes:greenAttrs range:NSMakeRange(0,strLength)];

    } else if (fltNumber == 0) {
        stringTres = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringTres length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringTres];
        [attStr setAttributes:orangeAttrs range:NSMakeRange(0,strLength)];
    }

    [arrayAtivos addObject:attStr];

}
4

3 回答 3

8

NSMutableOrderedSet是你想要的。只需替换NSMutableArrayNSMutableOrderedSet完成。

如果要过滤数组,请使用此

NSArray *array = // your array
NSMutableArray *filteredArray = [[[NSOrderedSet alloc] initWithArray: array] mutableCopy];

代替

arrayAtivos = [NSMutableArray new];

有了这个

arrayAtivos = [[NSMutableOrderedSet alloc] init];

并将类型更改arrayAtivosNSMutableOrderedSet

于 2013-01-25T00:20:44.973 回答
4

如果我理解正确,您可以在将对象添加到数组之前做一个简单的检查:

if (![arrayAtivos containsObject:attStr]) {
     [arrayAtivos addObject:attStr];
}
于 2013-01-25T00:14:50.070 回答
3

您可以将它们全部添加到不允许重复的 NSSet 中。

您可以从中获得一个数组,但如果这很重要,您将负责对它们进行排序。

于 2013-01-25T00:18:54.300 回答