在我的应用程序中,我从多个线程访问和更改可变数组。起初,当我尝试使用objectAtIndex
访问对象时会崩溃,因为索引超出了边界(该索引处的对象已经在另一个线程中从数组中删除)。我在互联网上搜索了如何解决这个问题,并决定尝试这个解决方案。我创建了一个带有NSMutableArray
属性的类,代码如下:
@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
,但仍然没有成功。我做错了什么,如何修复?
[NSMutableArray count]
(以及数组的每次访问)了吗? - trojanfoe