我的问题可能有一个非常明显的答案,我很想念。我有一个像这样的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
初始化连接。它转到connectionDidFinishLoading
,其中getImages
处理我必须操作并存储在数组中的数据。然后我使用reloadData
方法转到Collection View,这是我遇到各种问题的地方。
我需要访问dressURLS[i]
的元素,其中i = 0,1,2,3。但是,由于a的事实,循环非常复杂。集合视图重新加载b。异步调度。我无法让i
从0循环到
任何使这不那么复杂的解决方案?
答案 0 :(得分:1)
-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
if (connection == _firstConnection){
// Deal with the data
[self getImages];
[collectionView reloaddata]; // or self.collectionView (for property)
}
}
“讨论 调用此方法可重新加载集合视图中的所有项目。这会导致集合视图丢弃任何当前可见的项目并重新显示它们。“ - Apple
答案 1 :(得分:0)
你可以第一次使用BOOL&amp;第二次检查条件&amp;通过重新加载集合视图来显示图像。