我使用的是ios 7,我需要这样做:
在separete线程中,我想从网络创建图像并将其放入UIImageView。我需要每200毫秒做一次。
我的代码如下:
- (void)startPreview:(CGFloat)specialFramesRates;
{
if(isPreview)
return;
[Utils runOnThread:^{
[Log log:@"Start preview"]; //here we have a leak
isPreview = YES;
while(isPreview) {
[self getNewBitmap];
sleep(fpsTime);
if(!isPreview)
break;
if(checkAvabilityCam > 10)
break;
}
[Log log:@"Stoped preview"];
}];
}
- (void)getNewBitmap
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setTimeoutInterval:1];
[request setHTTPMethod:@"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if(delegate && response) {
checkAvabilityCam = 0;
//TODO what I should do here?
UIImage *image = [UIImage imageWithData:newImage]; //HERE IS LEAK !!!!
[delegate onShowImage:response]; //here I show image in main thread
image = nil; //With or without doesn't work
return;
}
checkAvabilityCam++;
if(delegate)
[delegate onShowDefaultImage];
}
在这行代码中我遇到了一个问题:
//TODO what I should do here?
UIImage *image = [UIImage imageWithData:newImage]; //HERE IS LEAK !!!!
[delegate onShowImage:response]; //here I show image in main thread
image = nil; //With or without doesn't work
我可以使用什么代替" [UIImage imageWithData:]" ?我尝试保存到文件和加载但具有相同的效果。我该怎么办?
答案 0 :(得分:4)
UIImage *image = [UIImage imageWithData:newImage]; //HERE IS LEAK !!!!
您正在此处创建自动释放的对象。由于您是在后台线程上执行此操作,因此除非您的线程具有自己的自动释放池,否则您创建的任何自动释放的对象都不会被释放。
如果您使用ARC,请使用@autoreleasepool关键字创建自动释放池:
@autoreleasepool {
UIImage *image = [UIImage imageWithData:newImage];
// Do stuff with image
}
如果您不使用ARC,请手动创建自动释放池:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = [UIImage imageWithData:newImage];
// Do stuff with image
[pool release];