在我的应用程序中,我正在访问并从多个线程更改可变数组.当我尝试使用objectAtIndex访问一个对象时,它开始崩溃,因为索引超出了边界(该索引处的对象已经从另一个线程中的数组中删除
@interface SynchronizedArray()
@property (retain, atomic) NSMutableArray *array;
@end
@implementation SynchronizedArray
- (id)init
{
self = [super init];
if (self)
{
_array = [[NSMutableArray alloc] init];
}
return self;
}
-(id)objectAtIndex:(NSUInteger)index
{
@synchronized(_array)
{
return [_array objectAtIndex:index];
}
}
-(void)removeObject:(id)object
{
@synchronized(_array)
{
[_array removeObject:object];
}
}
-(void)removeObjectAtIndex:(NSUInteger)index
{
@synchronized(_array)
{
[_array removeObjectAtIndex:index];
}
}
-(void)addObject:(id)object
{
@synchronized(_array)
{
[_array addObject:object];
}
}
- (NSUInteger)count
{
@synchronized(_array)
{
return [_array count];
}
}
-(void)removeAllObjects
{
@synchronized(_array)
{
[_array removeAllObjects];
}
}
-(id)copy
{
@synchronized(_array)
{
return [_array copy];
}
}
我使用这个类而不是旧的可变数组,但应用程序仍然在此行崩溃:return [_array objectAtIndex:index];我也试过这种方法与NSLock,但没有运气.我做错了什么以及如何解决这个问题?
我相信这个解决方案很差.考虑一下:>线程#1调用count,并告知阵列中有4个对象.
>数组未同步.
>线程#2在数组上调用removeObjectAtIndex:2.
>数组未同步.
> thread#1调用objectAtIndex:3并发生错误.
相反,您需要一个更高级别的锁定机制,其中锁定在步骤1和5的数组周围,而线程#2无法在这些步骤之间移除对象.
