【发布时间】:2014-08-28 07:36:54
【问题描述】:
我有一个与 iO 上的线程安全相关的相当令人费解的问题。
在一个单例对象中,我有一个包含字典元素的数组。字典元素包含与正在等待的资源(从互联网下载的图像)相关的对象和字符串。 当资源可用时(图像下载完成),我从数组中检索所有等待该特定资源的委托。
问题是数组(可变)可以被非常频繁地修改(来自不同的线程),并且它在被枚举时发生了修改。
我应该如何解决这个问题?我应该创建一个包含键的可变数组的静态字典吗?但是仍然可以枚举给定键的特定数组,同时为它添加另一个值....
这是(非常不安全的)代码:
- (void)addDelegate:(id<ImageDelegate>)delegate ForFileId:(NSString *)fileId
{
if (debug) { NSLog(@"[]adding delegate %@ for fileId: %@",delegate,fileId); }
NSDictionary *d = @{DELEGATE_KEY: delegate,
FILE_ID_KEY : fileId};
[self.delegatesArray addObject:d];
}
- (void)removeDelegate:(id<ImageDelegate>)delegate forImgUrl:(NSString *)imgUrl
{
NSString *fileId = [Utils formatLink:imgUrl];
if (debug) { NSLog(@"[]removing delegate %@ for fileId: %@",delegate,fileId); }
NSDictionary *toRemove;
for (NSDictionary *crtD in self.delegatesArray) {
if ([crtD[FILE_ID_KEY] isEqualToString:fileId] && [crtD[DELEGATE_KEY] isEqual:delegate]) {
toRemove = crtD;
break;
}
}
[self.delegatesArray removeObject:toRemove];
if (debug) { NSLog(@"[]removed delegate %@ for fileId: %@",toRemove,fileId); }
}
- (NSArray *)getAllDelegatesForFileId:(NSString *)fileId
{
NSMutableArray *requiredDelegates = [NSMutableArray new];
for (NSDictionary *crtD in self.delegatesArray) {
if ([crtD[FILE_ID_KEY] isEqualToString:fileId]) {
[requiredDelegates addObject:crtD];
}
}
NSArray *returnedArray = [NSArray arrayWithArray:requiredDelegates];
if (debug) { NSLog(@"[] found %d delegates for fileId:%@",[returnedArray count],fileId); }
return returnedArray;
}
【问题讨论】:
标签: ios arrays multithreading