我是 iOS 开发新手。我不知道 dispatch_get_main_queue()
所以我想从我的服务器图像 url 中获取图像大小,如
首先,我解析我的 JSON 数据并获取图像大小,如下所示
[self.feedArray addObjectsFromArray:[pNotification.userInfo valueForKey:@"items"]];
[self fillHeightArray];
在这里,我在我的 self.feedArray
中设置了解析数据,然后我得到了像这样的高度
-(void)fillHeightArray
{
NSMutableArray *requestArray=[[NSMutableArray alloc]init];
NSMutableArray *dataArray=[[NSMutableArray alloc]init];
for (int i=0; i<[self.feedArray count];i++)
{
NSString *urlString = [[self.feedArray objectAtIndex:i]valueForKey:@"photo"];
NSURL *imageFileURL = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:imageFileURL];
[requestArray addObject:urlRequest];
}
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
dispatch_async(downloadQueue, ^{
for (NSURLRequest *request in requestArray) {
[dataArray addObject:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]];
}
dispatch_async(callerQueue, ^{
for (int i=0; i<[dataArray count]; i++)
{
UIImage *imagemain=[UIImage imageWithData:[dataArray objectAtIndex:i]];
UIImage *compimage =[self resizeImage:imagemain resizeSize:CGSizeMake(screenWidth/2-16,180)];
CGSize size = CGSizeMake(screenWidth/2-16,compimage.size.height);
[self.cellHeights addObject:[NSValue valueWithCGSize:size]];
}
[GlobalClass StopSpinner:self.view];
self.cltItem.hidden=FALSE;
[self.cltItem reloadData];
[self.cltItem.collectionViewLayout invalidateLayout];
[[NSUserDefaults standardUserDefaults]setValue:@"1" forKey:Loading];
});
});
}
然后像这样调整我的图片大小
-(UIImage *)resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
float oldWidth = orginalImage.size.width;
float scaleFactor = size.width / oldWidth;
float newHeight = orginalImage.size.height * scaleFactor;
float newWidth = oldWidth * scaleFactor;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
[orginalImage drawInRect:CGRectMake(0,0,newWidth,newHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
所以,从这段代码我第一次得到了很好的结果但是当我想加载更多数据所以这段代码第二次运行时我得到了无效的图像大小
我不明白那里的问题是什么,但我认为我的
dispatch_queue_t callerQueue = dispatch_get_main_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL);
加载更多数据时出现问题。
请帮助我。
最佳答案
您总是在此行中添加对象:
[self.cellHeights addObject:[NSValue valueWithCGSize:size]];
当您第二次运行代码时,数组会变大,并且旧值仍然存在于其开头。当您第二次运行代码时,这可能会给您带来不好的结果。
编辑:
它可能会运行得更慢,因为您已经进行了一些保留周期/存在内存泄漏。在这种情况下,它第一次运行正常,每次额外运行都会变慢。除了 self.cellHeights 表不断增长之外,我确实没有看到您的代码有任何问题。检查过程的其余部分是否有每次变大的元素,并确保不再使用的对象被释放。
此外,尝试使用“构建和分析”[ALT + CMD + B]。这可能会指出一些内存泄漏或其他问题。
分析工具在定位泄漏方面也非常有效,您可以使用键盘上的 [CMD + I] 访问它们。
您可以尝试的另一件事是直接调用 main_queue,例如:
dispatch_async(dispatch_get_main_queue(), ^(void) {
//do sth
});
您将避免创建另一个对象,而且您在整个代码段中只使用一次 main_queue。
尝试这样做,如果你有任何收获,请告诉我。
关于ios - dispatch_get_main_queue() 运行得不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32739571/