sharedArray
我有一个创建速度很慢的对象数组。我首先创建它们并将它们同时插入到数组中。之后,一些读者同时访问 this sharedArray
,获取其中的对象并以自己的方式处理它。我遇到了崩溃,我认为是由于未正确访问共享资源造成的。我做错了吗?
我正在使用 ARC,iOS 目标部署版本为 5.1。设置资源时出现错误EXC_BAD_ACCESS
(在代码中标记)。
非常感谢!
//Creation of the array
dispatch_queue_t constructionQueue = dispatch_queue_create("constructionQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(numberOfSlowObjects, constructionQueue, ^(size_t i) {
__block SlowObject *slowOb = [[SlowObject alloc] init];
dispatch_sync(dispatch_get_main_queue(), ^{
[sharedArray setObject:slowOb atIndexedSubscript:i]; //HERE I GET THE ERROR
});
});
dispatch_release(constructionQueue);
//Accessing the array from the different readers
dispatch_queue_t readersQueue = dispatch_queue_create("readersQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(readers.count, readersQueue, ^(size_t i) {
Reader *reader = [readers objectAtIndex:i];
dispatch_queue_t processQueue = dispatch_queue_create("processQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(numberOfSlowObjects, processQueue, ^(size_t j) {
__block SlowObject *slowOb;
dispatch_sync(dispatch_get_main_queue(), ^{
slowOb = [sharedArray objectAtIndex:j];
});
[reader process:slowOb];
});
dispatch_release(processQueue);
});
dispatch_release(readersQueue);
以及sharedArray
(共享资源)延迟初始化的代码:
- (NSMutableArray *) sharedArray
{
if(!_sharedArray){
_sharedArray = [[NSMutableArray alloc] initWithCapacity:numberOfSlowObjects];
for(int i=0;i<numberOfSlowObjects;i++) [_sharedArray addObject:[NSNumber numberWithInt:0]]; //null initialization;
}
return _sharedArray;
}