如何避免在NSArray中插入重复的对象?

Mar*_*ida 1 objective-c duplicates nsarray

好吧,我遇到一个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];

}
Run Code Online (Sandbox Code Playgroud)

Bry*_*hen 8

NSMutableOrderedSet就是你想要的.只需更换NSMutableArrayNSMutableOrderedSet和完成.

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

NSArray *array = // your array
NSMutableArray *filteredArray = [[[NSOrderedSet alloc] initWithArray: array] mutableCopy];
Run Code Online (Sandbox Code Playgroud)

更换

arrayAtivos = [NSMutableArray new];
Run Code Online (Sandbox Code Playgroud)

有了这个

arrayAtivos = [[NSMutableOrderedSet alloc] init];
Run Code Online (Sandbox Code Playgroud)

和改变的类型arrayAtivos,以NSMutableOrderedSet