简体   繁体   中英

How to filter UIColor object in NSMutableArray

I am generating random colors and storing in NSmutableArray like this

for(int i=0; i<1000; i++) {
    UIColor *c = [self colorGen];
    [_cArray addObject:c];
}

I want to check that every time I add color to array its not repeating, How I apply predicate to _cArray to check color return by [self colorGen] method is not already exist in _cArray , for example _cArray already contains red color after 10 iteration [self colorGen] again return red color so how I can avoid adding it again my array.

    for(int i=0; i<1000; i++) {
        UIColor *c = [self colorGen];

      if (![_cArray containsObject:c]) {

           [_cArray addObject:c];

        }  
}

plz use this code

NSMutableSet *colors = [NSMutableSet set];
while (colors.count < 1000) {
    [colors addObject:[self colorGen]];
}

example code for the way UIColor objects are compared:

NSMutableSet *colors = [NSMutableSet set];

UIColor *color1 = [UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:1];
UIColor *color2 = [UIColor colorWithRed:0.1 green:0.2 blue:0.3 alpha:1];

[colors addObjectsFromArray:@[color1, color2]];

NSLog(@"%lu", (unsigned long)colors.count);

this code prints 1 indicating that both colors are treated to be equal!

you can do like,

 for(int i=0; i<1000; i++) {
    UIColor *c = [self colorGen];

    if (![_cArray containsObject:c] ) {

         [_cArray addObject:c];

    }
    else{

        NSLog(@"already there");
    }


}

Change in methods colorGen it should return hex value of UIColor

for(int i=0; i<1000; ) {
    NSString *strCode = [self colorGen];

    if (![_cArray containsObject:strCode] ) {

         [_cArray addObject:strCode];
        i++;

    }
    else{

        NSLog(@"already there");
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM