Dar*_*zur 0 memory-leaks uiimage
我正在使用 ios 7,我需要做:
在单独的线程中,我想从网络创建图像并将其放入 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];
}
Run Code Online (Sandbox Code Playgroud)
在这行代码中,我有一个问题:
//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
Run Code Online (Sandbox Code Playgroud)
我可以用什么代替 "[UIImage imageWithData:]" ?我尝试保存到文件并加载但效果相同。我该怎么办?
UIImage *image = [UIImage imageWithData:newImage]; //HERE IS LEAK !!!!
Run Code Online (Sandbox Code Playgroud)
您正在此处创建一个自动释放的对象。由于您是在后台线程上执行此操作,因此除非您的线程拥有自己的自动释放池,否则您创建的任何自动释放对象都不会被释放。
如果您使用的是 ARC,请使用 @autoreleasepool 关键字创建一个自动释放池:
@autoreleasepool {
UIImage *image = [UIImage imageWithData:newImage];
// Do stuff with image
}
Run Code Online (Sandbox Code Playgroud)
如果您不使用 ARC,请手动创建一个自动释放池:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = [UIImage imageWithData:newImage];
// Do stuff with image
[pool release];
Run Code Online (Sandbox Code Playgroud)