我发现了类似的问题,但是-containsObject
没有像我预期的那样工作。
我的问题是NSMutableArray -containsObject
方法在不应该返回 true 时返回 true,
当尝试生成随机唯一颜色并添加到数组时。
检查是否存在的最佳方法是什么NSMutableArray
包含具有相同值的对象。
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]);
The
NSLog()
always says array count is 1.
新编辑:
你的结构for()
循环也是错误的。您在循环开始之前声明 UIColor。您应该在循环开始后声明颜色:
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。
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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)