Segurança do thread do NSMutableArray
No meu aplicativo, estou acessando e alterando uma matriz mutável de vários threads. No começo, estava travando quando eu estava tentando acessar um objeto comobjectAtIndex
, porque o índice estava fora dos limites (o objeto nesse índice já foi removido da matriz em outro segmento). Procurei na internet como resolver esse problema e resolvi tentar issosolução .Eu fiz uma aula comNSMutableArray
propriedade, consulte o seguinte código:
@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];
}
}
e eu uso essa classe em vez da antiga matriz mutável, mas o aplicativo ainda está travando nesta linha:return [_array objectAtIndex:index];
Eu tentei também essa abordagem comNSLock
, mas sem sorte. O que estou fazendo de errado e como consertar isso?