当我使用dispatch_apply向nscountset添加一些数据时,我在模拟器中遇到了崩溃但是iphone。并获得一条消息" - [__ NSArrayI isEqual:]:消息发送到解除分配的实例0x60000024c5a0" ,我找不到它是怎么发生的。
CGSize thumbSize = CGSizeMake(200,200);
NSCountedSet *cls2 = [NSCountedSet setWithCapacity:thumbSize.width * thumbSize.height];
dispatch_apply(thumbSize.width, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
int x = (int)index;
for (int y = 0; y < thumbSize.height; y++) {
if(y<x){
continue;
}
int offset = 4*(x*y);
int red = data[offset];
int green = data[offset+1];
int blue = data[offset+2];
int alpha = data[offset+3];
NSArray *clr2 = @[@(red),@(green),@(blue),@(alpha)];
[cls2 addObject:clr2];
}
});
崩溃在[cls2 addobject:clr2]中;日志是&#34; - [__ NSArrayI isEqual:]:消息发送到解除分配的实例0x60000024c5a0&#34;。 并且在我的函数中有所有代码,我想在图像中获得最多颜色。
CGSize thumbSize = CGSizeMake(200, 200);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, thumbSize.width, thumbSize.height, 8, thumbSize.width * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
CGContextDrawImage(context, drawRect, self.CGImage);
CGColorSpaceRelease(colorSpace);
unsigned char *data = CGBitmapContextGetData(context);
if (data == NULL)
{
return nil;
}
NSCountedSet *cls2 = [NSCountedSet setWithCapacity:thumbSize.width * thumbSize.height];
dispatch_apply(thumbSize.width, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
int x = (int) index;
for (int y = 0; y < thumbSize.height; y++)
{
if (y < x)
{
continue;
}
int offset = 4 * (x * y);
int red = data[offset];
int green = data[offset + 1];
int blue = data[offset + 2];
int alpha = data[offset + 3];
NSArray *clr3 = @[@(red), @(green), @(blue), @(alpha)];
[cls2 addObject:clr3];
}
});
CGContextRelease(context);
NSEnumerator *enumerator = [cls2 objectEnumerator];
NSArray *curColor = nil;
NSArray *maxColor = nil;
NSUInteger maxCount = 0;
while ((curColor = [enumerator nextObject]) != nil)
{
NSUInteger tmpCount = [cls2 countForObject:curColor];
if (tmpCount < maxCount) {
continue;
}
maxCount = tmpCount;
maxColor = curColor;
}
NSLog(@"colors: RGB A %f %d %d %d",[maxColor[0] floatValue],[maxColor[1] intValue],[maxColor[2] intValue],[maxColor[3] intValue]);
return [UIColor colorWithRed:([maxColor[0] intValue]/255.0f) green:([maxColor[1] intValue]/255.0f) blue:([maxColor[2] intValue]/255.0f) alpha:([maxColor[3] intValue]/255.0f)];
答案 0 :(得分:0)
NSCountedSet
不是线程安全的 - reference。尝试从并发线程中改变一个将会产生不可预测的结果 - 正如您所发现的那样。
使用不带for
的简单dispatch_apply
循环,如果需要,在后台线程上调度,处理您的数据,或通过在序列调度上调度来保护您的NSCountedSet
更新队列中。