gpt4 book ai didi

ios - NSMutableArray 线程安全

转载 作者:可可西里 更新时间:2023-11-01 06:20:46 25 4
gpt4 key购买 nike

在我的应用程序中,我从多个线程访问和更改一个可变数组。开始时,当我尝试使用 objectAtIndex 访问对象时它崩溃了,因为索引超出范围(该索引处的对象已从另一个线程的数组中删除)。我在网上搜索了如何解决这个问题,我决定试试这个 solution .我用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. 线程 #1 调用 count 并被告知数组中有 4 个对象。
  2. 数组不同步。
  3. 线程 #2 在数组上调用 removeObjectAtIndex:2
  4. 数组不同步。
  5. 线程 #1 调用 objectAtIndex:3 并发生错误。

相反,您需要一个更高级别的锁定机制,其中在步骤 1 和 5 中都围绕数组锁定,并且线程 #2 无法在这些步骤之间删除对象。

关于ios - NSMutableArray 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21139581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com