Kur*_*kay 5 contains objective-c nsmutablearray
我发现了类似的问题,但是-containsObject没有像我期望的那样工作.
我的问题是NSMutableArray -containsObject当它不应该,当尝试生成随机的UNIQUE颜色并添加到数组时,该方法返回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]);
Run Code Online (Sandbox Code Playgroud)
NSLog()总说数组数为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);
}
Run Code Online (Sandbox Code Playgroud)
UIColor 不使用integer值,它使用float值。尝试将您的值integer除以 255,然后将它们设置为 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];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3845 次 |
| 最近记录: |