I found similar questions, but -containsObject is not working like I expect.
My problem is the NSMutableArray -containsObject method returns true when it shouldn't,
when trying to generate random UNIQUE colors and add to an array.
What is the best way to check if NSMutableArray contains an object with same values.
NSMutableArray *color_arr=[NSMutableArray array];
UIColor *t;
for(int i=0; i<100; i+=1)
{
int r = arc4random()%256;
int g = arc4random()%256;
int b = arc4random()%256;
t=[UIColor colorWithRed:r green:g blue:b alpha:255];
if (![color_arr containsObject:t])
[color_arr addObject:t];
//[t release];//is t need to be released here on non-arc project? well Im not sure.
}
NSLog(@"total:%d",[color_arr count]);
NSLog() always says array count is 1.
New Edit:
The structure of your for() loop is wrong too. You are declaring the UIColor before the loop begins. You should be declaring the color AFTER the loop begins:
for (i=0;i<100;i++) {
int rInt = arc4random()%256;
float rFloat = (float)rInt/255.0f;
//same with gInt, bInt
//make gFloat and bFloat this way
UIColor *t = [UIColor colorWithRed:rFloat green:gFloat blue:bFloat alpha:1];
if (![color_arr containsObject:t]) {
[color_arr addObject:t];
}
NSLog(@"%i",color_arr.count);
}
UIColor doesn't use integer values, it uses float values. Try dividing your integer by 255 and then setting those as r, g, b.
Like:
int rInt = arc4random()%256;
float rFloat = (float)rInt/255.0f;
//same with gInt, bInt
//make gFloat and bFloat this way
t = [UIColor colorWithRed:rFloat green:gFloat blue:bFloat alpha:1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With