NSMutableArray containsObject返回true,但不应 [英] NSMutableArray containsObject returns true, but it shouldnt

查看:89
本文介绍了NSMutableArray containsObject返回true,但不应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了类似的问题,但是 -containsObject 无法正常工作.

I found similar questions, but -containsObject is not working like I expect.

我的问题是 NSMutableArray -containsObject 方法在不应该返回true的情况下,尝试生成随机UNIQUE颜色并将其添加到数组时.

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.

检查 NSMutableArray 是否包含具有相同值的对象的最佳方法是什么.

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()始终表示数组计数为1.


The NSLog() always says array count is 1.

推荐答案

for()循环的结构也是错误的.您需要在循环开始之前声明UIColor.您应该在循环开始后声明颜色:

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不使用 integer 值,而是使用 float 值.尝试将 integer 除以255,然后将其设置为r,g,b.

UIColor doesn't use integer values, it uses float values. Try dividing your integer by 255 and then setting those as r, g, b.

赞:

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];

这篇关于NSMutableArray containsObject返回true,但不应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆