0

我的问题可能有一个非常明显的答案,我错过了。我有一个像这样的 NSURLConnection:

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *urlstring = [NSString stringWithFormat:@"http://127.0.0.1:8000/image/"];
NSMutableURLRequest *postRequest = [NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:urlstring]
                                    cachePolicy:NSURLRequestUseProtocolCachePolicy
                                    timeoutInterval:30.0];
[postRequest setHTTPMethod:@"POST"];
self.firstConnection = [[NSURLConnection alloc] initWithRequest:postRequest delegate:self];

}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
if (connection == _firstConnection){
    // Deal with the data
    [self getImages];
    [self.collectionView reloadData];
}

-(void)getImages
{
NSError *error;
NSMutableArray* images= [NSJSONSerialization JSONObjectWithData:_data options:0 error:&error];
NSUInteger arrayLength = [images count];


dressURLS = [[NSMutableArray alloc] init];
for (NSInteger i=0;i<arrayLength;i++)
{
    NSString *temp = [images[i] objectForKey:@"image"];
    [dressURLS addObject:temp];
}
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

static NSString *identifier = @"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *dressImageView = (UIImageView *)[cell viewWithTag:100];

NSString *clothesurl = dressURLS[i]; //i value????
NSString *url =[NSString stringWithFormat:@"http://127.0.0.1:8000/media/%@",clothesurl];
NSURL *imageURL = [NSURL URLWithString:url];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI
        dressImageView.image = [UIImage imageWithData:imageData];
    });
});

return cell;

}

我知道,代码很混乱。这就是它的工作原理。viewDidLoad初始化连接。它会处理我必须操作和存储在数组中的数据connectionDidFinishLoadinggetImages然后我使用该reloadData方法转到集合视图,这是我遇到各种问题的地方。

我需要访问dressURLS[i]i=0,1,2,3 的元素。但是由于 a. 集合视图被重新加载 b. 异步调度。我无法i从 0 循环到 3。

有什么解决方案可以让这变得不那么复杂吗?

4

2 回答 2

1
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
if (connection == _firstConnection){
    // Deal with the data
    [self getImages];
    [collectionView reloaddata]; // or self.collectionView (for property)
}

}

“讨论调用此方法重新加载集合视图中的所有项目。这会导致集合视图丢弃任何当前可见的项目并重新显示它们。” - 苹果

于 2013-09-13T13:03:01.723 回答
0

您可以第一次和第二次使用 BOOL 检查条件并通过重新加载集合视图来显示图像。

于 2013-09-13T13:18:17.080 回答