【发布时间】:2011-12-14 17:47:27
【问题描述】:
我真的需要这方面的帮助! 我正在构建一个包含大量图块的地图……比如 200x200 的 50 像素小图块。这些图块位于 UIScrollView 中,因此我可以在地图上拖动自己!真的很好用吧?好吧,因为地图中的子视图太多,所以速度非常慢。
好的,所以我在滚动时加载子视图!问题是,这也需要一些时间,使滚动有点滞后/缓慢。你能帮我改进这个功能吗?我没主意了。找到了 Grand Central Dispatch,但我不知道如何使用它。
这是我的代码
-(void)loadMapTiles {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(1, queue,
^(size_t row) {
int radiusX = 11;
int radiusY = 7;
int y = currentCoord.y-radiusY;
for(int x = currentCoord.x-radiusX; x < currentCoord.x+radiusX+1; x++) {
int currTag = mapSize.width*(y-1)+x;
if(![mapScroller viewWithTag:currTag]) {
UIImageView *mapTile = [[UIImageView alloc] initWithFrame:CGRectMake(50*x, 50*y, 50, 50)];
int mapNo = (rand() % 20) + 1;
if(mapNo > 11) {
mapNo = 1;
}
mapTile.image = [UIImage imageNamed:[NSString stringWithFormat:@"desert_map%d_50.gif", mapNo]];
//Tag the mapTile so that we can find it again!
[mapTile setTag:currTag];
[mapContentView addSubview:mapTile];
[mapTile release];
}
if(x == currentCoord.x+radiusX && y < currentCoord.y+radiusY) {
x = currentCoord.x-radiusX-1;
y++;
}
}
//Remove the other tiles outside the radius!
for (UIView *mapTile in [mapContentView subviews]) {
if(mapTile.frame.origin.x / 50 < currentCoord.x-radiusX || mapTile.frame.origin.x / 50 > currentCoord.x+radiusX || mapTile.frame.origin.y / 50 < currentCoord.y-radiusY || mapTile.frame.origin.y / 50 > currentCoord.y+radiusY) {
[mapTile removeFromSuperview];
}
}
});
}
以及上面调用地图构建函数的函数:
-(void)scrollViewDidScroll:(UIScrollView *)myScrollView {
CGPoint newCoord = CGPointMake((int)(myScrollView.contentOffset.x + myScrollView.frame.size.width/2) /50, (int)(myScrollView.contentOffset.y + myScrollView.frame.size.height/2) /50);
if(newCoord.x != currentCoord.x || newCoord.y != currentCoord.y) {
currentCoord = newCoord;
[self loadMapTiles];
}
}
【问题讨论】:
-
dispatch_apply(1, queue, ...)的意义何在?我想你想要dispatch_async(queue, ^(){...}) -
如果我这样做,我得到的只是
Collection <CALayerArray: 0x3dc7c0> was mutated while being enumerated.:( 我不能异步编辑滚动视图吗? -
UIKit 调用应该在主线程上
标签: objective-c ios performance uiscrollview load