在我的应用程序中,我正在从多个线程访问和更改可变数组。一开始,当我尝试使用以下命令访问对象时,它崩溃了objectAtIndex
,因为索引超出范围(该索引处的对象已从另一个线程的数组中删除)。我在网上搜索了如何解决这个问题,我决定尝试这个solution https://stackoverflow.com/a/3521873/2298998.我上了一堂课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
,但没有运气。我做错了什么以及如何解决这个问题?
我认为这个解决方案很差。考虑一下:
- 线程 #1 调用
count
并被告知数组中有 4 个对象。
- 数组不同步。
- 线程 #2 调用
removeObjectAtIndex:2
在阵列上。
- 数组不同步。
- 线程 #1 调用
objectAtIndex:3
并发生错误。
相反,您需要一个更高级别的锁定机制,其中锁位于步骤 1 和 5 中的数组周围,并且线程 #2 无法删除这些步骤之间的对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)