gpt4 book ai didi

ios - NSMutableArray 线程安全问题 - iOS

转载 作者:行者123 更新时间:2023-11-29 13:31:10 25 4
gpt4 key购买 nike

我有一个在 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/

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