ios - NSMutableArray 线程安全问题 - iOS

标签 ios xcode thread-safety nsmutablearray

我有一个在 ASIHTTPRequest 进程中使用的 NSMutableArray。数据加载完成后,NSMutableArray 存储信息。当我将数据添加为

[MyArray addObject];

我没有任何错误。但是,当我将数据插入为

[MyArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];

我有 malloc 错误或索引超出范围异常问题。我认为这是线程安全故障。有什么解决办法吗?

编辑: 在 appdelegate.h 中

 @interface{
  NSMutableArray *imageArray;
 }

在 appdelegate.m 中

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
imageArray = [[NSMutableArray alloc] init];
return YES;
}

在 AsyncImageView.h 中

@interface{
  AppDelegate *delegate
}

AsyncImageView.m

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

  delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [delegate.imageArray insertObject:[UIImage imageWithData:data] atIndex:buttonTag];

 }

最佳答案

如果没有看到您的代码很难说,但我怀疑这是线程问题。当您调用 insertObject:atIndex: 时,您必须能够保证数组中至少已经有那么多对象。查看您的代码并查看您添加对象的位置,并确保每个场景都会导致您添加足够的对象,insertObject:atIndex 不会失败。

希望下一个事实对您来说是显而易见的,但为了以防万一,我要指出 initWithCapacity: 确实向数组添加任何元素。许多人认为确实如此,从而导致您所描述的确切问题。

根据您的评论,解决方案可能是用一堆 NSNull 对象预填充您的数组,或者使用 NSDictionary 而不是数组。

编辑 这是一个快速的 NSDictionary 示例:

经过进一步审查,您实际上需要一个 NSMutableDictionary,因为您要动态更新其内容。您不能使用整数作为键,因此您必须将整数“包装”在 NSNumber 对象中。 (请注意,您可以使用任何对象作为键,而不仅仅是 NSNumber。)

像这样存储一个对象:

[myDictionary setObject:[UIImage imageWithData:data] forKey:[NSNumber numberWithInt:buttonTag]];

稍后像这样访问它:

myImage = [myDictionary objectForKey:[NSNumber numberWithInt:buttonTag]];

当然,更多信息可以在 Apple 文档中找到,也可以快速搜索“NSDictionary example”。

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

相关文章:

ios - Apple App Store 提交 - 模拟账户

php - 从iOS解析php中的json正文

c# - 队列的线程安全处理

ios - 如何让iOS应用程序在启动时自动识别是从哪个应用程序商店下载的?

objective-c - 对于 xCode 中的 XMLparser,我要测试什么字符串名称?

ios - 当我在 Xcode 4.6.2 中单击 RUN 时,我的 iPhone 应用程序不断崩溃

ios - 'present modally' View Controller 中的 ScrollView 不工作

ios - 使用 SwiftUI 制作按钮闪烁动画

java - 是否为线程更新了公共(public)静态变量? (它是线程安全的吗?)

java - Notify()/NotifyAll() 全部在退出同步块(synchronized block)之前